【发布时间】:2019-07-02 08:45:49
【问题描述】:
我有一个多索引列。上级是一些人,下级是一些措施。我想创建一些新列,它们是度量的衍生物(例如滚动平均值)。我希望我可以使用一些索引切片来实现这一点,但现在唉。过去我在这里发现了一些类似的问题,但它们是老问题,我怀疑还有更现代的 Pythonic 解决方案。
下面是玩具示例,我在其中演示了我正在尝试对一列执行什么操作(有效),但如果我尝试将其应用于所有子列分组,则显示相同的方法会失败。
index = pd.DatetimeIndex(start='2018-1-1',periods=5,freq="M")
persons = ['mike', 'dave', 'matt']
measures = ['spin', 'drag', 'bezel']
cols = pd.MultiIndex.from_product([persons, measures],names=['human', 'measure'])
xf = pd.DataFrame(index=index, data=np.random.rand(5,9), columns=cols)
idx = pd.IndexSlice
#Doing this to one specific column works
xf.loc[:,idx['mike','bezel']].rolling(window=2).mean()
xf.loc[:,idx['mike','roll']] = xf.loc[:,idx['mike','bezel']].rolling(window=2).mean()
#Trying to create a 'roll2' measure for all the humans (mike, dave,matt) doesn't work
xf.loc[:,idx[:,'roll2']] = "placeholder" #xf.loc[:,idx['mike','bezel']].rolling(window=2).mean()
xf
【问题讨论】:
标签: python pandas multi-index