Divide a multi column dataframe by a one column dataframe

Question:

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
Asked By: Stacey

||

Answers:

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)
Answered By: Phoenix

An alternative approach, by chaining the reindex and div methods to perform the division operation, and align the index labels.

z_axis = y_axis.reindex(x_axis.index).div(x_axis.values, axis=0)
z_axis.index, z_axis.columns = pd.to_datetime(z_axis.index), ['A', 'B']
print(z_axis)

                   A    B
2021-01-01  6.000000 -5.0
2021-01-02 -0.666667 -1.0
2021-01-03 -1.750000  0.5
Answered By: Jamiu S.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.