For two dataframes:
df_1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df_2 = pd.DataFrame({'A': [3], 'B': [4]})
How do I divide all values in df_1 columns A and B by the respective values of A and B in df_2 so that:
df_3 = pd.DataFrame({'A': [0.33, 0.66], 'B': [0.75, 1]})
I need to perform this operation over two large dataframes with the same headings. Please, scalable solutions.
CodePudding user response:
You can use slicing of df_2
as Series:
df_1.div(df_2.iloc[0])
Or:
df_1.div(df_2.squeeze())
Output:
A B
0 0.333333 0.75
1 0.666667 1.00
CodePudding user response:
IIUC, you can try
df = df_1.div(pd.concat([df_2]*len(df_1), ignore_index=True)).round(2)
print(df)
A B
0 0.33 0.75
1 0.67 1.00
CodePudding user response:
You can try df_3 = pd.DataFrame(df_1.values / df_2.values, columns=list(df_1.columns.values))