列表中的Pandas groupby值

时间:2019-04-16 03:21:13

标签: python pandas list group-by

我正在尝试从groupby pandas返回df。我希望不对输出值求和merged。但是以下merges是适当的lists

import pandas as pd

d = ({
    'Id' : [1,2,2,1],                 
    'Val' : ['A','B','B','A'],                  
    'Output' : [[1,2,3,4,5],[5,3,3,2,1],[6,7,8,9,1],[6,7,8,9,1]],                       
     })

df = pd.DataFrame(data = d)

df = df.groupby(['Id','Val']).agg({'Output':'sum'}, axis = 1)

出局:

                                Output
Id Val                                
1  A    [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
2  B    [5, 3, 3, 2, 1, 6, 7, 8, 9, 1]

预期输出:

                                Output
Id Val                                
1  A    [7,9,11,13,6]
2  B    [11,10,11,11,2]

3 个答案:

答案 0 :(得分:3)

或使用单线转换为np.array

df = df.groupby(['Id','Val']).apply(lambda x: x.Output.apply(np.array).sum())
print(df)

输出:

Id  Val
1   A        [7, 9, 11, 13, 6]
2   B      [11, 10, 11, 11, 2]
dtype: object

答案 1 :(得分:2)

您可以将list更改为numpy array,然后

df.Output=df.Output.apply(np.array)

df.groupby(['Id','Val']).Output.apply(lambda x : np.sum(x))
Out[389]: 
Id  Val
1   A        [7, 9, 11, 13, 6]
2   B      [11, 10, 11, 11, 2]
Name: Output, dtype: object

答案 2 :(得分:1)

另一种使用zip而不是应用apply的解决方案,

df.groupby(['Id','Val']).Output.apply(lambda x: [sum(i) for i in list(zip(*x))])

Id  Val
1   A        [7, 9, 11, 13, 6]
2   B      [11, 10, 11, 11, 2]