如何从pandas groupby中的多个列中获取唯一值

Fab*_*nna 8 python pandas

从这个数据帧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
Run Code Online (Sandbox Code Playgroud)

我想在c列上执行groupby 以获取l1l2列的唯一值.对于我可以做的一列:

g = df.groupby('c')['l1'].unique()
Run Code Online (Sandbox Code Playgroud)

正确返回:

c
1    [a, b]
2    [c, b]
Name: l1, dtype: object
Run Code Online (Sandbox Code Playgroud)

但使用:

g = df.groupby('c')['l1','l2'].unique()
Run Code Online (Sandbox Code Playgroud)

收益:

AttributeError: 'DataFrameGroupBy' object has no attribute 'unique'
Run Code Online (Sandbox Code Playgroud)

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

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

有没有办法将此方法应用于groupby,以获得类似的东西:

c
1    [a, b, d]
2    [c, b, e, f]
Name: l1, dtype: object
Run Code Online (Sandbox Code Playgroud)

Yaa*_*ler 31

或者,您可以使用agg

g = df.groupby('c')['l1','l2'].agg(['unique'])
Run Code Online (Sandbox Code Playgroud)

  • 您如何将“unique”和“.join”组合在同一个聚合中? (2认同)

ayh*_*han 15

你可以这样做apply:

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


Ch3*_*teR 15

另一种选择是GroupBy.agg使用set

df.groupby('c').agg(set)

       l1      l2
c                
1  {a, b}  {d, b}
2  {c, b}  {e, f}
Run Code Online (Sandbox Code Playgroud)

  • 当 l1 和 l2 中的值不可散列(例如时间戳)时,您可能会遇到麻烦。否则固溶。 (3认同)