Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Divide a multi column dataframe by a one column dataframe

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

                       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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading