假设我有一个像这样的多索引 DataFrame:
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)
输出:
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
现在我创建一个系列,其索引与我的 DataFrame 的列相匹配:
s = pd.Series([1,2,3], index=["col1", "col2", "col3"])
我可以将 DataFame 中 bucket 1
中的值除以系列,如下所示:
df.loc["bucket 1"].div(s)
输出:
col1 col2 col3
q1 0.061384 0.182097 -0.500829
q2 0.562352 -0.022418 0.080825
q3 0.373411 -0.339214 -0.420661
但是,如果我尝试使用此计算通过 .loc
设置 DataFrame 中的值,它只会创建 NaN:
df.loc["bucket 1"] = df.loc["bucket 1"].div(s)
输出:
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
我做错了什么?如何在 DataFrame 中进行计算?
最佳答案
只需使用 .values
设置值:
df.loc["bucket 1"]=df.loc["bucket 1"].div(s).values
print(df)
col1 col2 col3
bucket 1 q1 -0.149856 0.220604 -0.048464
q2 -0.791260 -0.199646 0.148115
q3 -0.712257 -0.264074 -0.266497
bucket 2 q1 -1.120164 -0.290546 0.577589
q2 -0.149522 -0.221203 -0.566872
q3 -1.002036 -2.233220 -1.206849
关于python - Pandas - 将 DataFrame 值除以 MultiIndex DataFrame 中的 Series,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55106625/