在pandas dataframe中groupby之后将多个列合并转换为dict

我有一个数据帧

df = pd.DataFrame({"a":[1,1,1,2,2,2,3,3], "b":["a","a","a","b","b","b","c","c"], "c":[0,0,1,0,1,1,0,1], "d":["x","y","z","x","y","y","z","x"]})


    a   b   c   d
0   1   a   0   x
1   1   a   0   y
2   1   a   1   z
3   2   b   0   x
4   2   b   1   y
5   2   b   1   y
6   3   c   0   z
7   3   c   1   x

我想对a列和b列进行分组,以获得以下输出:

    a   b   e
0   1   a   [{'c': 0, 'd': 'x'}, {'c': 0, 'd': 'y'}, {'c': 1, 'd': 'z'}]
1   2   b   [{'c': 0, 'd': 'x'}, {'c': 1, 'd': 'y'}, {'c': 1, 'd': 'y'}]
2   3   c   [{'c': 0, 'd': 'z'}, {'c': 1, 'd': 'x'}]

 解决方案:

new=ddf.groupby(['a','b'])[['c','d']].apply(lambda x : x.to_dict('records')).to_frame('e').reset_index()
Out[13]: 
   a  b                                                  e
0  1  a  [{'c': 0, 'd': 'x'}, {'c': 0, 'd': 'y'}, {'c':...
1  2  b  [{'c': 0, 'd': 'x'}, {'c': 1, 'd': 'y'}, {'c':...
2  3  c           [{'c': 0, 'd': 'z'}, {'c': 1, 'd': 'x'}]

 

或者,我们可以:

df['e'] = df[['c', 'd']].agg(lambda s: dict(zip(s.index, s.values)), axis=1)
df1 = df.groupby(['a', 'b'])['e'].agg(list).reset_index()

你可能感兴趣的:(pandas,python,pandas,python,dataframe)