I have 2 dataframes (x_axis and y_axis). I wish to divide y_axis by x_axis, however I get a NaN error. As you can see the index of the two dataframes is the same.
import pandas as pd
x_axis = pd.DataFrame({'I': [1, -3, 4],},
index=['2021-01-01', '2021-01-02', '2021-01-03'])
y_axis = pd.DataFrame({'A': [6, 2, -7],
'B': [-5, 3, 2]},
index=['2021-01-01', '2021-01-02', '2021-01-03'])
z_axis = y_axis / x_axis
the output I get is:
A B I
2021-01-01 NaN NaN NaN
2021-01-02 NaN NaN NaN
2021-01-03 NaN NaN NaN
my desired output is:
A B
01/01/2021 6 -5
02/01/2021 -0.666666667 -1
03/01/2021 -1.75 0.5
>Solution :
the division operation is not aligning the indices of the two dataframes properly. before division you have to reindex them. change z_axis = y_axis / x_axis line to:
y_axis = y_axis.reindex(x_axis.index)
z_axis = y_axis.divide(x_axis['I'], axis=0)
z_axis.index = pd.to_datetime(z_axis.index).strftime('%m/%d/%Y')
print(z_axis)