Pandas Groupby独特的多列

时间:2017-11-22 12:11:51

标签: python python-3.x pandas group-by

我有一个数据框。

import pandas as pd
df = pd.DataFrame(           
{'number': [0,0,0,1,1,2,2,2,2], 'id1': [100,100,100,300,400,700,700,800,700], 'id2': [100,100,200,500,600,700,800,900,1000]})

   id1   id2  number
0  100   100       0
1  100   100       0
2  100   200       0
3  300   500       1
4  400   600       1
5  700   700       2
6  700   800       2
7  800   900       2
8  700  1000       2

(这代表了一个更大的数据帧,我正在使用〜数百万行)。

我可以将groupby().unique应用于一列:

df.groupby(['number'])['id1'].unique()

number
0         [100]
1    [300, 400]
2    [700, 800]
Name: id1, dtype: object

df.groupby(['number'])['id2'].unique()

number
0               [100, 200]
1               [500, 600]
2    [700, 800, 900, 1000]
Name: id2, dtype: object

我想同时在两个列上执行唯一操作,以便在数据帧中对其进行排序:

number
0               [100, 200]
1     [300, 400, 500, 600]
2    [700, 800, 900, 1000]

当我尝试为两列执行此操作时,我收到错误:

pd.Data.Frame(df.groupby(['number'])['id1', 'id2'].unique())

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-15-bfc6026e241e>", line 9, in <module>
    df.groupby(['number'])['id1', 'id2'].unique()
  File "C:\Python34\lib\site-packages\pandas\core\groupby.py", line 498, in __getattr__
    (type(self).__name__, attr))
AttributeError: 'DataFrameGroupBy' object has no attribute 'unique'

怎么办?是否最好使用多指数?

编辑:此外可以按如下方式获得输出:

number
0 100
0 200
1 300
1 400
1 500
1 600
2 700
2 800
2 900
2 1000

1 个答案:

答案 0 :(得分:6)

您可以按[]选择所有列:

s = (df.groupby(['number'])['id1', 'id2']
       .apply(lambda x: pd.unique(x.values.ravel()).tolist()))

print (s)
number
0               [100, 200]
1     [300, 500, 400, 600]
2    [700, 800, 900, 1000]
dtype: object

或者:

s2 = (df.groupby(['number'])['id1', 'id2']
        .apply(lambda x: np.unique(x.values.ravel()).tolist()))
print (s2)
number
0               [100, 200]
1     [300, 400, 500, 600]
2    [700, 800, 900, 1000]
dtype: object

编辑:

如果需要输出为列,请先按stack然后drop_duplicates重新整形:

df1 = (df.set_index('number')[['id1', 'id2']]
         .stack()
         .reset_index(level=1, drop=True)
         .reset_index(name='a')
         .drop_duplicates())
print (df1)
    number     a
0        0   100
5        0   200
6        1   300
7        1   500
8        1   400
9        1   600
10       2   700
13       2   800
15       2   900
17       2  1000