【发布时间】:2019-08-02 01:09:55
【问题描述】:
假设我有一个像这样的多索引 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 中进行计算?
【问题讨论】:
-
您需要只将一组除以
s,还是最终将其应用于整个DataFrame? -
在我的真实用例中,我将有一个不同的系列来划分每个桶。
标签: python pandas dataframe series multi-index