Search code examples
pythonpandasdataframedivision

Python: Divide row in one DataFrame by all rows in another DataFrame


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.


Solution

  • 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