I was just wondering whether anyone had a good way to divide a whole Pandas DataFrames (row-by-row) by another row in a different DataFrame.
Example: Say I had one DF that was this: col1: 1 3 col1: 2 4
and another like this: col1: 2 col2: 2
How could I easily arrive at this DF: col1: 0.5 1.5 col2: 1 2
Thanks!
CodePudding user response:
df1 = pd.DataFrame({'a': [1, 3, 5], 'b': [2, 4, 6]})
df2 = pd.DataFrame({'a': [2, 4], 'b': [5, 10]})
df1:
Out[7]:
a b
0 1 2
1 3 4
2 5 6
df2:
a b
0 2 5
1 4 10
df3 = df1 divided by first row of df2:
df3 = pd.DataFrame(df1.values / df2.loc[0].values, columns=df1.columns)
df3:
a b
0 0.5 0.4
1 1.5 0.8
2 2.5 1.2
CodePudding user response:
Simply use div
, or /
:
df1.div(df2.iloc[0])
# or
df1/df2.iloc[0]
Output:
a b
0 1.0 1.0
1 3.0 2.0
Used input:
df1 = pd.DataFrame({'a': [1, 3], 'b': [2, 4]})
df2 = pd.DataFrame({'a': [1], 'b': [2]})