How to group dataframe rows into list in pandas groupby

前端 未结 12 2137
日久生厌
日久生厌 2020-11-21 04:56

I have a pandas data frame df like:

a b
A 1
A 2
B 5
B 5
B 4
C 6

I want to group by the first column and get second col

12条回答
  •  迷失自我
    2020-11-21 05:42

    If performance is important go down to numpy level:

    import numpy as np
    
    df = pd.DataFrame({'a': np.random.randint(0, 60, 600), 'b': [1, 2, 5, 5, 4, 6]*100})
    
    def f(df):
             keys, values = df.sort_values('a').values.T
             ukeys, index = np.unique(keys, True)
             arrays = np.split(values, index[1:])
             df2 = pd.DataFrame({'a':ukeys, 'b':[list(a) for a in arrays]})
             return df2
    

    Tests:

    In [301]: %timeit f(df)
    1000 loops, best of 3: 1.64 ms per loop
    
    In [302]: %timeit df.groupby('a')['b'].apply(list)
    100 loops, best of 3: 5.26 ms per loop
    

提交回复
热议问题