2016-11-04 89 views
5

到數據框提供以下df在熊貓新柱 - 添加一系列應用列表GROUPBY

Id other concat 
0 A  z  1 
1 A  y  2 
2 B  x  3 
3 B  w  4 
4 B  v  5 
5 B  u  6 

我想要的結果與new列與分組值列表

Id other concat   new 
0 A  z  1  [1, 2] 
1 A  y  2  [1, 2] 
2 B  x  3 [3, 4, 5, 6] 
3 B  w  4 [3, 4, 5, 6] 
4 B  v  5 [3, 4, 5, 6] 
5 B  u  6 [3, 4, 5, 6] 

這類似於對這些問題:

grouping rows in list in pandas groupby

Replicating GROUP_CONCAT for pandas.DataFrame

但是,它是適用你df.groupby('Id')['concat'].apply(list),這比數據框尺寸較小的Series拿到分組,原來的數據幀。

我曾嘗試下面的代碼,但它並沒有這個適用於數據框:

import pandas as pd 
df = pd.DataFrame({'Id':['A','A','B','B','B','C'], 'other':['z','y','x','w','v','u'], 'concat':[1,2,5,5,4,6]}) 
df.groupby('Id')['concat'].apply(list) 

我知道transform可用於分組適用於dataframes,但它並沒有在這種情況下工作。

>>> df['new_col'] = df.groupby('Id')['concat'].transform(list) 
>>> df 
    Id concat other new_col 
0 A  1  z  1 
1 A  2  y  2 
2 B  5  x  5 
3 B  5  w  5 
4 B  4  v  4 
5 C  6  u  6 
>>> df['new_col'] = df.groupby('Id')['concat'].apply(list) 
>>> df 
    Id concat other new_col 
0 A  1  z  NaN 
1 A  2  y  NaN 
2 B  5  x  NaN 
3 B  5  w  NaN 
4 B  4  v  NaN 
5 C  6  u  NaN 

回答

4

groupbyjoin

df.join(df.groupby('Id').concat.apply(list).to_frame('new'), on='Id') 

enter image description here

3

那麼優雅(慢..)的解決方案,但希望這是這裏只是作爲一種替代。

def func(gr): 
    gr['new'] = [list(gr.concat)] * len(gr.index) 
    return gr 
df.groupby('Id').apply(func) 

%timeit df.groupby('Id').apply(func) 
100 loops, best of 3: 4.18 ms per loop 

%timeit df.join(df.groupby('Id').concat.apply(list).to_frame('new'), on='Id') 
1000 loops, best of 3: 1.69 ms per loop 
1

使用transform[x.tolist()][x.values]

In [1396]: df.groupby('Id')['concat'].transform(lambda x: [x.tolist()]) 
Out[1396]: 
0   [1, 2] 
1   [1, 2] 
2 [3, 4, 5, 6] 
3 [3, 4, 5, 6] 
4 [3, 4, 5, 6] 
5 [3, 4, 5, 6] 
Name: concat, dtype: object 

In [1397]: df['new'] = df.groupby('Id')['concat'].transform(lambda x: [x.tolist()]) 

In [1398]: df 
Out[1398]: 
    Id other concat   new 
0 A  z  1  [1, 2] 
1 A  y  2  [1, 2] 
2 B  x  3 [3, 4, 5, 6] 
3 B  w  4 [3, 4, 5, 6] 
4 B  v  5 [3, 4, 5, 6] 
5 B  u  6 [3, 4, 5, 6]