如何从Pandas Groupby中的多个列中获取唯一值 [英] How to get unique values from multiple columns in a pandas groupby

查看:444
本文介绍了如何从Pandas Groupby中的多个列中获取唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从此数据帧df开始:

df = pd.DataFrame({'c':[1,1,1,2,2,2],'l1':['a','a','b','c','c','b'],'l2':['b','d','d','f','e','f']})

   c l1 l2
0  1  a  b
1  1  a  d
2  1  b  d
3  2  c  f
4  2  c  e
5  2  b  f

我想对c列执行分组,以获取l1l2列的唯一值.对于一栏我可以做:

I would like to perform a groupby over the c column to get unique values of the l1 and l2 columns. For one columns I can do:

g = df.groupby('c')['l1'].unique()

正确返回的

:

that correctly returns:

c
1    [a, b]
2    [c, b]
Name: l1, dtype: object

但使用:

g = df.groupby('c')['l1','l2'].unique()

返回:

AttributeError: 'DataFrameGroupBy' object has no attribute 'unique'

我知道我可以(除其他外)获得两列的唯一值:

I know I can get the unique values for the two columns with (among others):

In [12]: np.unique(df[['l1','l2']])
Out[12]: array(['a', 'b', 'c', 'd', 'e', 'f'], dtype=object)

有没有一种方法可以将此方法应用于groupby以获得类似于以下内容的信息:

Is there a way to apply this method to the groupby in order to get something like:

c
1    [a, b, d]
2    [c, b, e, f]
Name: l1, dtype: object

推荐答案

您可以使用apply做到这一点:

You can do it with apply:

import numpy as np
g = df.groupby('c')['l1','l2'].apply(lambda x: list(np.unique(x)))

这篇关于如何从Pandas Groupby中的多个列中获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆