Here is my code and I want to get the expected output, but, division of dataframes does not work, what is wrong here?
import pandas as pd
data1 = {'name':['A', 'C', 'D'], 'cond_a':['B','B','B'], 'value':[10,12,14]}
data2 = {'name':['A', 'C', 'D','D','A'], 'cond_a':['G','G','G','G','G'], 'value':[5,6,7,3,2]}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
df1.set_index('name', inplace=True)
df2.set_index('name', inplace=True)
df2['new_col'] = df2['value'] / df1['value']
expected output:
cond_a value new_col
name
A G 5 5/10
C G 6 6/12
D G 7 7/14
D G 3 3/14
A G 2 2/10
As long as df1 has a unique index, you can reindex it on df2 when performing the division:
df2['new_col'] = df2['value'] / df1['value'].reindex(df2.index)
The resulting output:
cond_a value new_col
name
A G 5 0.500000
C G 6 0.500000
D G 7 0.500000
D G 3 0.214286
A G 2 0.200000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With