-
哔哔one
你可以用groupby在感兴趣的列上分组,然后apply list每一组:In [1]:# create the dataframe df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]})dfOut[1]: a b0 A 11 A 22 B 53 B 54 B 45 C 6[6 rows x 2 columns]In [76]:df.groupby('a')['b'].apply(list)Out[76]:aA [1, 2]B [5, 5, 4]C [6]Name: b, dtype: object
-
江户川乱折腾
如果性能很重要,请降到numpy级别: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测试:In [301]: %timeit f(df)1000 loops, best of 3: 1.64 ms per loopIn [302]: %timeit df.groupby('a')['b'].
apply(list)100 loops, best of 3: 5.26 ms per loop
-
POPMUISE
就像你说的groupbya的方法pd.DataFrame对象可以完成这项工作。例 L = ['A','A','B','B','B','C'] N = [1,2,5,5,4,6] import pandas as pd df = pd.DataFrame(zip(L,N),columns = list('LN')) groups = df.groupby(df.L) groups.groups {'A': [0, 1], 'B': [2, 3, 4], 'C': [5]}它给出了各组的分类描述和索引描述。要获取单个组的元素,可以这样做,例如 groups.get_group('A') L N 0 A 1 1 A 2 groups.get_group('B') L N 2 B 5 3 B 5 4 B 4