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

Dividing Data Frame rows by different values

I’ve got a simple Data Frame. I want to divide each row by a different value (in this case, my rows are a sum of weekly data and I want to divide by the number of weeks in a month). When I do the following nothing happens, I just get the same values prior to the division attempt. I tried using a constant in the divide function as well, but same results. Obviously I’m missing a step. Any thoughts?

number_of_weeks = [4,4,5,1]

for i in range(len(df_Plot.index)):
    df_Plot.iloc[[i][:]].div(number_of_weeks[i])

               A       B       C       D
Date                                      
2023-01-31  0.0325  3.6375  0.0000   0.025
2023-02-28  0.0300  1.7000  0.0000   0.000
2023-03-31  0.0000  0.4375  0.1875   0.000
2023-04-30  0.0250  0.5500  0.4250   0.000

>Solution :

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

Try this:

df_Plot = df_Plot.div(number_of_weeks, axis=0)

… or this:

df_Plot = (df_Plot.T / number_of_weeks).T

Output:

                   A         B       C        D
Date
2023-01-31  0.008125  0.909375  0.0000  0.00625
2023-02-28  0.007500  0.425000  0.0000  0.00000
2023-03-31  0.000000  0.087500  0.0375  0.00000
2023-04-30  0.025000  0.550000  0.4250  0.00000

Although there’s no need to iterate as in the sample code in your question, since div() allows for vectorized operation as above, it’s possible to get the same result using iteration like this:

for i in range(len(df_Plot)):
    df_Plot.iloc[i,:] = df_Plot.iloc[i,:].div(number_of_weeks[i])
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