gpt4 book ai didi

python - 如何将列添加到多索引数据帧?

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:41 25 4
gpt4 key购买 nike

我有一个如下所示的多索引数据框:

       ACA FP Equity            UCG IM Equity            
LAST PRICE VOLUME LAST PRICE VOLUME
date
2010-01-04 12.825 5879617.0 15.0292 10844639.0
2010-01-05 13.020 6928587.0 14.8092 16456228.0
2010-01-06 13.250 5290631.0 14.6834 10446450.0
2010-01-07 13.255 5328586.0 15.0292 31900341.0
2010-01-08 13.470 7160295.0 15.1707 40750768.0

如果我想在数据框中为每个股权添加第三列,语法是什么?例如:

df['ACA FP Equity']['PriceVolume'] = df['ACA FP Equity']['LAST PRICE']*3

但我想为每个 Assets 都这样做,而不是手动添加每个 Assets 。

提前致谢。

最佳答案

如果您需要所有 LAST PRICE 列乘以 3 使用 slicers 选择它们并重命名列名称:

idx = pd.IndexSlice
df1 = df.loc[:, idx[:, 'LAST PRICE']].rename(columns={'LAST PRICE':'PriceVolume'}) * 3
print (df1)
ACA FP Equity UCG IM Equity
PriceVolume PriceVolume
2010-01-04 38.475 45.0876
2010-01-05 39.060 44.4276
2010-01-06 39.750 44.0502
2010-01-07 39.765 45.0876
2010-01-08 40.410 45.5121

然后你需要 concat 输出:

print (pd.concat([df,df1], axis=1))
ACA FP Equity UCG IM Equity ACA FP Equity \
LAST PRICE VOLUME LAST PRICE VOLUME PriceVolume
2010-01-04 12.825 5879617.0 15.0292 10844639.0 38.475
2010-01-05 13.020 6928587.0 14.8092 16456228.0 39.060
2010-01-06 13.250 5290631.0 14.6834 10446450.0 39.750
2010-01-07 13.255 5328586.0 15.0292 31900341.0 39.765
2010-01-08 13.470 7160295.0 15.1707 40750768.0 40.410

UCG IM Equity
PriceVolume
2010-01-04 45.0876
2010-01-05 44.4276
2010-01-06 44.0502
2010-01-07 45.0876
2010-01-08 45.5121

另一种不使用 concat 的解决方案是从 selected_df 的列创建元组,然后分配输出:

idx = pd.IndexSlice
selected_df = df.loc[:, idx[:, 'LAST PRICE']]

new_cols = [(x, 'PriceVolume') for x in selected_df.columns.levels[0]]
print (new_cols)
[('ACA FP Equity', 'PriceVolume'), ('UCG IM Equity', 'PriceVolume')]

df[new_cols] = selected_df * 3
print(df)
ACA FP Equity UCG IM Equity ACA FP Equity \
LAST PRICE VOLUME LAST PRICE VOLUME PriceVolume
2010-01-04 12.825 5879617.0 15.0292 10844639.0 38.475
2010-01-05 13.020 6928587.0 14.8092 16456228.0 39.060
2010-01-06 13.250 5290631.0 14.6834 10446450.0 39.750
2010-01-07 13.255 5328586.0 15.0292 31900341.0 39.765
2010-01-08 13.470 7160295.0 15.1707 40750768.0 40.410

UCG IM Equity
PriceVolume
2010-01-04 45.0876
2010-01-05 44.4276
2010-01-06 44.0502
2010-01-07 45.0876
2010-01-08 45.5121

关于python - 如何将列添加到多索引数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41160170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com