Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide all rows in a panda Dataframe except for one specific row?

Currently, I am working with a pandas.DataFrame that I need to divide the entire dataframe by a certain value except for one row. It is easy to divide the entire dataframe by one value, however I would like to keep one of the rows the exact same. For example, if I had a dataframe like below:

  A      B      C      D
10000  10000  10000  10000 
10000  10000  10000  10000 
10000  10000  10000  10000 
10000  10000  10000  10000 
  1      1      1      1   
10000  10000  10000  10000 
10000  10000  10000  10000 

I want to divide all of the rows by the value of 1000 except for the 5th row, which I would like all the values to stay the same of 1. So, the new dataframe would look like this:

 A   B   C   D
10  10  10  10
10  10  10  10
10  10  10  10
10  10  10  10
 1   1   1   1   
10  10  10  10 
10  10  10  10 

Is there a simple way to accomplish this? I feel like I am missing something very basic. I have tried using loc, iloc, mul, & div but can not get them to work concurrently.

like image 815
vdub32 Avatar asked Feb 06 '18 03:02

vdub32


1 Answers

If you save the row of interest, and then divide the entire dataframe by the desired value. You can then restore the row of interest afterwards.

Code:

def df_divide_by_excect_row(in_df, divisor, row_to_ignore):
    row_to_save = in_df.iloc[row_to_ignore]
    new_df = in_df / divisor
    new_df.iloc[row_to_ignore] = row_to_save
    return new_df

Test Code:

import pandas as pd

df = pd.read_fwf(StringIO(u"""
      A      B      C      D
    10000  10000  10000  10000 
    10000  10000  10000  10000 
    10000  10000  10000  10000 
    10000  10000  10000  10000 
      1      1      1      1   
    10000  10000  10000  10000 
    10000  10000  10000  10000"""), header=1)

print(df)
print(df_divide_by_excect_row(df, 1000, 4))

Results:

       A      B      C      D
0  10000  10000  10000  10000
1  10000  10000  10000  10000
2  10000  10000  10000  10000
3  10000  10000  10000  10000
4      1      1      1      1
5  10000  10000  10000  10000
6  10000  10000  10000  10000

      A     B     C     D
0  10.0  10.0  10.0  10.0
1  10.0  10.0  10.0  10.0
2  10.0  10.0  10.0  10.0
3  10.0  10.0  10.0  10.0
4   1.0   1.0   1.0   1.0
5  10.0  10.0  10.0  10.0
6  10.0  10.0  10.0  10.0
like image 160
Stephen Rauch Avatar answered Oct 05 '22 08:10

Stephen Rauch