Home > front end >  Python: Divide row in one DataFrame by all rows in another DataFrame
Python: Divide row in one DataFrame by all rows in another DataFrame

Time:06-22

I have two DataFrames as follows:

df1:
       A      B      C       D
index
    0  10000  20000  30000   40000

df2:
      time    type  A     B      C     D
index
    0 5/2020  unit  1000  4000   900   200
    1 6/2020  unit  7000  2000   600   4000

I want to divide df1.iloc[0] by all rows in df2 to get the following:

df:
      time    type  A     B    C       D
index
    0 5/2020  unit  10    5    33.33   200
    1 6/2020  unit  1.43  10   50      10

I tried to use df1.iloc[0].div(df2.iloc[:]) but that gave me NaNs for all rows other than the 0 index. Any suggestions would be greatly appreciated. Thank you.

CodePudding user response:

Let us do

df2.update(df2.loc[:,df1.columns].rdiv(df1.iloc[0]))
df2
Out[861]: 
     time  type          A     B          C      D
0  5/2020  unit  10.000000   5.0  33.333333  200.0
1  6/2020  unit   1.428571  10.0  50.000000   10.0

CodePudding user response:

another way to do it, using numpy divide

df2.update(np.divide(df.to_numpy()[:,:], df2.loc[:,df.columns]))
df2
    time    type    A           B       C           D
0   5/2020  unit    10.000000   5.0     33.333333   200.0
1   6/2020  unit    1.428571    10.0    50.000000   10.0

CodePudding user response:

You can use div.

df = df2.apply(lambda x:df1.iloc[0].div(x[df1.columns]), axis=1)

print(df):

               A     B          C      D
index                                   
0      10.000000   5.0  33.333333  200.0
1       1.428571  10.0  50.000000   10.0
  • Related