向多级数据框添加子列

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

我的数据框看起来像

    First    Second
    A   B    A   B 
1   50  60   70  100
2   20  5    10  30
3   35  45   60  50

我想使用

.diff()
在每个顶级列中添加一个新的子列,所以它看起来像(在本例中,采用
B
列的差异)

       First          Second
    A   B   Diff     A    B    Diff
1   50  60  NaN      70   100  NaN
2   20  5   -55      10   30   -70
3   35  45  40       60   50   20 

我认为应该有一种干净的方法来做到这一点,而无需 for 循环和其他低效的本机 python 操作,但我不确定如何实现。

python pandas dataframe multiple-columns
1个回答
0
投票

一种可能的解决方案:

df[[(c, "Diff") for c in df.columns.unique(0)]] = df.loc[:, (slice(None), "B")].diff()
df = df.sort_index(axis=1)

print(df)

打印:

  First           Second           
      A   B  Diff      A    B  Diff
1    50  60   NaN     70  100   NaN
2    20   5 -55.0     10   30 -70.0
3    35  45  40.0     60   50  20.0
© www.soinside.com 2019 - 2024. All rights reserved.