gpt4 book ai didi

python - 多索引数据帧上的操作

转载 作者:行者123 更新时间:2023-12-01 01:29:18 25 4
gpt4 key购买 nike

我想将列添加到 Pandas 多索引数据框中,其中将包含对其他列执行操作的结果。

我有一个与此类似的数据框:

first   bar     baz     
second one two one two
A 5 2 9 2
B 6 4 7 6
C 5 4 5 1

现在,对于数据框中的每个组,我想添加一列“三”,该列等于“一”列减去“二”列:

first   bar             baz     
second one two three one two three
A 5 2 3 9 2 7
B 6 4 2 7 6 1
C 5 4 1 5 1 4

实际上,我的数据框要大得多。我正在努力寻找这个(希望)简单问题的答案。如有任何建议,我们将不胜感激。

最佳答案

使用DataFrame.xs选择一个两个级别并减去,然后在MultiIndex.from_product列中创建MultiIndex :

df1 = df.xs('one', axis=1, level=1) - df.xs('two', axis=1, level=1)
df1.columns = pd.MultiIndex.from_product([df1.columns, ['three']])
print (df1)
bar baz
three three
A 3 7
B 2 1
C 1 4

然后concat为原始和更改订单使用 reindex通过助手MultiIndex:

mux = pd.MultiIndex.from_product([['bar','baz'], ['one','two','three']], 
names=df.columns.names)
df = pd.concat([df, df1], axis=1).reindex(columns=mux)
print (df)
first bar baz
second one two three one two three
A 5 2 3 9 2 7
B 6 4 2 7 6 1
C 5 4 1 5 1 4

关于python - 多索引数据帧上的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53047331/

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