在多索引数据框中分配新列

问题描述 投票:0回答:1

我有以下多索引数据框:

我想添加一个标记为

returns
的新列,并指定应用于
close
列的百分比变化,即

bars.loc[symbol, 'returns'] = bars.loc[symbol]['close'].pct_change()

挑战在于

returns
列没有按预期填充。所以通过下面的代码片段,这就是我得到的

for symbol in symbols:
   bars.loc[symbol, 'returns'] = bars.loc[symbol]['close'].pct_change()
print(df.loc[symbols[0]].tail())

返回列的值为 NaN,我在这里做错了什么?

python python-3.x pandas dataframe multi-index
1个回答
0
投票

您需要将值分配给新列。假设 DF 是条形且交易品种索引是 level_0,则对于循环,您可以使用下面的代码。这假设您想要 10.0 作为回报百分比,而不是 0.1。

idx_list = bars.index.levels[0]

for symbol in idx_list:
        x = bars.loc[symbol, 'close'].pct_change()*100
        bars.loc[symbol, 'returns'] = x.values
© www.soinside.com 2019 - 2024. All rights reserved.