gpt4 book ai didi

python - 通过求和执行分组后保留多索引列结构

转载 作者:行者123 更新时间:2023-12-01 00:13:00 26 4
gpt4 key购买 nike

我有一个三级多索引列。在最低级别,我想添加一个小计列。

因此,在这里的示例中,我希望有一个新列 zone: day, person:dave, find:'subtotal' ,其中值 = 49+27+63=138。对于 zoneperson 的所有其他组合也是如此。 enter image description here

cols = pd.MultiIndex.from_product([['day', 'night'], ['dave', 'matt', 'mike'], ['gems', 'rocks', 'paper']])
rows = pd.date_range(start='20191201', periods=5, freq="d")
data = np.random.randint(0, high=100,size=(len(rows), len(cols)))
xf = pd.DataFrame(data, index=rows, columns=cols)
xf.columns.names = ['zone', 'person', 'find']

我可以使用 xf.groupby(level=[0,1], axis="columns").sum() 生成正确的小计数据,但随后我丢失了 find 级别的列,它只留下 zoneperson 级别。我需要名为 subtotal 的第三级列,以便我可以将其与原始 xf 数据框join。但我无法找到一种很好的 Pythonic 方法来将第三个级别添加回多重索引中。

enter image description here

最佳答案

您可以先使用sum,然后使用MultiIndex.from_product新级别:

df = xf.sum(level=[0,1], axis="columns")

df.columns = pd.MultiIndex.from_product(df.columns.levels + [['subtotal']])
print (df)
day night
dave matt mike dave matt mike
subtotal subtotal subtotal subtotal subtotal subtotal
2019-12-01 85 99 163 210 93 252
2019-12-02 38 113 101 211 110 135
2019-12-03 145 75 122 181 165 176
2019-12-04 220 184 173 179 134 192
2019-12-05 126 77 29 184 178 199

然后通过concat一起加入与 DataFrame.sort_index :

df = pd.concat([xf, df], axis=1).sort_index(axis=1)
print (df)
zone day \
person dave matt mike
find gems paper rocks subtotal gems paper rocks subtotal gems paper
2019-12-01 33 96 24 153 34 89 90 213 15 51
2019-12-02 74 48 61 183 94 83 2 179 75 4
2019-12-03 88 85 51 224 65 3 52 120 95 80
2019-12-04 43 28 60 131 43 14 77 134 88 54
2019-12-05 41 72 44 157 63 77 37 177 8 66

zone ... night \
person ... dave matt mike
find ... rocks subtotal gems paper rocks subtotal gems paper rocks
2019-12-01 ... 24 102 19 49 4 72 43 57 92
2019-12-02 ... 90 206 96 55 92 243 75 58 68
2019-12-03 ... 29 182 11 90 85 186 9 20 46
2019-12-04 ... 30 84 25 55 89 169 98 41 85
2019-12-05 ... 73 167 52 90 49 191 51 80 37

zone
person
find subtotal
2019-12-01 192
2019-12-02 201
2019-12-03 75
2019-12-04 224
2019-12-05 168

[5 rows x 24 columns]

关于python - 通过求和执行分组后保留多索引列结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59498134/

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