0

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.

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Actually both div or rdiv throws ZeroDivisionError if one of the divisor is 0, how to avoid it without complex logic of checking if zero is present in series or not. Is there any easy way?
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.