Suppose I have a multi-index DataFrame such as this:
import numpy as np
import pandas as pd
ix = pd.MultiIndex.from_product([['bucket 1', 'bucket 2'], ['q1', 'q2', 'q3']])
col = ['col1', 'col2', 'col3']
df = pd.DataFrame(np.random.randn(6, 3), ix, col)
Output:
col1 col2 col3
bucket 1 q1 0.061384 0.364194 -1.502486
q2 0.562352 -0.044836 0.242474
q3 0.373411 -0.678429 -1.261984
bucket 2 q1 0.884109 -0.070899 0.085305
q2 -0.010463 1.463259 -0.572882
q3 -0.419821 -0.916151 0.032110
Now I create a Series with the index matching the columns of my DataFrame:
s = pd.Series([1,2,3], index=["col1", "col2", "col3"])
I can divide the values in bucket 1 in the DataFame by the Series like so:
df.loc["bucket 1"].div(s)
Output:
col1 col2 col3
q1 0.061384 0.182097 -0.500829
q2 0.562352 -0.022418 0.080825
q3 0.373411 -0.339214 -0.420661
However if I try to use this calculation to set the values in the DataFrame using .loc, it just creates NaNs:
df.loc["bucket 1"] = df.loc["bucket 1"].div(s)
Output:
col1 col2 col3
bucket 1 q1 NaN NaN NaN
q2 NaN NaN NaN
q3 NaN NaN NaN
bucket 2 q1 0.884109 -0.070899 0.085305
q2 -0.010463 1.463259 -0.572882
q3 -0.419821 -0.916151 0.032110
What am I doing wrong? How do I make the calculations in the DataFrame?
sor ultimately apply this to the entireDataFrame?