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 :
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])