[英]Pandas Dataframe Groupby multiple columns then sum
假設每個 Python 代碼如下:
import pandas as pd
import numpy as np
在 Pandas 中,如果我有一個 2 列的數據框,其中一個是數字數組,我可以對數組的值求和以獲得單個數組。
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar'], 'numbers' : [np.array([1, 2, 3, 4]),np.array([2, 4, 2, 4]),np.array([2, 3, 4, 5]),np.array([1, 3, 5, 7])]} )
df['arrays'].sum()
我什至可以按第一列分組,然后對第二列求和以獲得每組的總和:
grpA = df.groupby('A')
grpA.sum()
但是,如果除了數組列之外我還有多個其他列,比如其他 2 列,那么當我嘗試按前兩列分組並對數組列求和時,我會得到一個ValueError: Function does not reduce
:
df2 = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar'],'B': ['la', 'la', 'al', 'al'],'numbers' : [np.array([1, 2, 3, 4]),np.array([2, 4, 2, 4]),np.array([2, 3, 4, 5]),np.array([1, 3, 5, 7])]} )
grpAB = df2.groupby(['A','B'])
grpAB.sum()
在 SQL 中,如果我可以對數組求和,以下內容將起作用:
select A, B, sum(numbers)
from df2
group by A, B
有沒有辦法成功地按多列分組並對 Pandas 中的最后一個數組列求和?
您可以使用lambda
表達式。 iat
表達式采用系列中第一個元素的標量值(這里只是數字列表),然后對結果求和。
>>> df2.groupby(['A', 'B']).numbers.apply(lambda x: x.iat[0].sum())
A B
bar al 16
la 12
foo al 14
la 10
Name: numbers, dtype: int64
一個可能的解決方案是
df2 = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar'],'B': ['la', 'la', 'al', 'al'],'numbers' : [np.array([1, 2, 3, 4]),np.array([2, 4, 2, 4]),np.array([2, 3, 4, 5]),np.array([1, 3, 5, 7])]} )
grouped = df2.groupby(['A','B'])
#set up empty arrays to append data from below loop
array=[]
index=[]
#loop through the grouped data and sum up the array numbers
for i,j in grouped:
array.append({'numbers':j.numbers.sum()})
index.append(i)
#put summed array back into a dataframe
print pd.DataFrame((array),index=index)
df2 = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar'],'B': ['la', 'la', 'al', 'al'],'numbers' : [np.array([1, 2, 3, 4]),np.array([2, 4, 2, 4]),np.array([2, 3, 4, 5]),np.array([1, 3, 5, 7])]} )
Out[42]:
A B numbers
0 foo la [1, 2, 3, 4]
1 bar la [2, 4, 2, 4]
2 foo al [2, 3, 4, 5]
3 bar al [1, 3, 5, 7]
grpAB = df2.groupby(['A','B'])
res = grpAB.apply(lambda x : x.numbers.sum())
Out[43]:
A B
bar al [1, 3, 5, 7]
la [2, 4, 2, 4]
foo al [2, 3, 4, 5]
la [1, 2, 3, 4]
dtype: object
pd.DataFrame(res , columns = ['numbers'])
Out[44]:
numbers
A B
bar al [1, 3, 5, 7]
la [2, 4, 2, 4]
foo al [2, 3, 4, 5]
la [1, 2, 3, 4]
# if you want to reset the index
pd.DataFrame(res , columns = ['numbers']).reset_index()
Out[45]:
A B numbers
0 bar al [1, 3, 5, 7]
1 bar la [2, 4, 2, 4]
2 foo al [2, 3, 4, 5]
3 foo la [1, 2, 3, 4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.