[英]Pandas: groupby to sum subsets of columns
我有一個多列的pandas數據框。 我想計算此列的各個子集的總和,並為每組列分配一個名稱。
是否可以使用groupby或其他熊貓方法來實現此目的?
設定:
import numpy as np; np.random.seed(1)
import pandas as pd
df = pd.DataFrame(np.random.randint(0, 10, (3, 5)), columns=['A', 'B', 'C', 'D', 'E'])
columns_groups = {'First': ['A', 'B', 'C'],
'Second': ['D', 'E'],
'Some': ['A', 'C', 'D'],
'All': ['A', 'B', 'C', 'D', 'E']}
所需的輸出:(是否有更好的解決方案?)
out = {}
for name, group in columns_groups.items():
out[name] = df[group].sum(axis=1)
out = pd.DataFrame(out)
out
Out[22]:
All First Second Some
0 27 22 5 19
1 23 8 15 13
2 17 11 6 9
我的嘗試:
df.groupby(columns_groups, axis=1).sum(axis=1)
Out[21]:
Empty DataFrame
Columns: []
Index: [0, 1, 2]
這樣可以嗎?
pd.DataFrame({k: df[v].sum(axis=1) for k, v in columns_groups.items()})
All First Second Some
0 27 22 5 19
1 23 8 15 13
2 17 11 6 9
和您所做的一樣,只是理解力強。
只是另一種有趣的方式,將reindex
與MultiIndex
一起MultiIndex
df=df.reindex(columns=sum(columns_groups.values(),[]))
t=[(x,z ) for x , y in columns_groups.items() for z in y]
df.columns=pd.MultiIndex.from_tuples(t)
df.sum(level=0,axis=1)
First Second Some All
0 22 8 18 30
1 17 9 16 26
2 6 15 14 21
您實際上可以通過單行熊貓操作來完成。 內存效率更高,超級簡單
file['sum']=file.sum(axis=1, skipna = True)
下面的輸出
All First Second sum
0 27 22 5 54.0
1 23 8 15 46.0
2 17 11 6 34.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.