我有一个熊猫数据帧df像:
a b
A 1
A 2
B 5
B 5
B 4
C 6
我想按第一列分组,并将第二列作为行中的列表:
A [1,2]
B [5,5,4]
C [6]
是否有可能使用pandas groupby来做这样的事情?
我有一个熊猫数据帧df像:
a b
A 1
A 2
B 5
B 5
B 4
C 6
我想按第一列分组,并将第二列作为行中的列表:
A [1,2]
B [5,5,4]
C [6]
是否有可能使用pandas groupby来做这样的事情?
当前回答
只是一个补充。熊猫。数据透视表更通用,似乎更方便:
"""data"""
df = pd.DataFrame( {'a':['A','A','B','B','B','C'],
'b':[1,2,5,5,4,6],
'c':[1,2,1,1,1,6]})
print(df)
a b c
0 A 1 1
1 A 2 2
2 B 5 1
3 B 5 1
4 B 4 1
5 C 6 6
"""pivot_table"""
pt = pd.pivot_table(df,
values=['b', 'c'],
index='a',
aggfunc={'b': list,
'c': set})
print(pt)
b c
a
A [1, 2] {1, 2}
B [5, 5, 4] {1}
C [6] {6}
其他回答
有点老了,但我是被指引到这里的。有办法把它按多个不同的列分组吗?
"column1", "column2", "column3"
"foo", "val1", 3
"foo", "val2", 0
"foo", "val2", 3
"bar", "other", 99
:
"column1", "column2", "column3"
"foo", "val1", [ 3 ]
"foo", "val2", [ 0, 3 ]
"bar", "other", [ 99 ]
基于@B。M的答案,这里是一个更通用的版本,并更新为与更新的库版本一起工作:(numpy版本1.19.2,pandas版本1.2.1) 这个解决方案也可以处理多指标:
然而,这并没有经过严格的测试,请谨慎使用。
如果性能是重要的,下降到numpy级别:
import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame({'a': np.random.randint(0, 10, 90), 'b': [1,2,3]*30, 'c':list('abcefghij')*10, 'd': list('hij')*30})
def f_multi(df,col_names):
if not isinstance(col_names,list):
col_names = [col_names]
values = df.sort_values(col_names).values.T
col_idcs = [df.columns.get_loc(cn) for cn in col_names]
other_col_names = [name for idx, name in enumerate(df.columns) if idx not in col_idcs]
other_col_idcs = [df.columns.get_loc(cn) for cn in other_col_names]
# split df into indexing colums(=keys) and data colums(=vals)
keys = values[col_idcs,:]
vals = values[other_col_idcs,:]
# list of tuple of key pairs
multikeys = list(zip(*keys))
# remember unique key pairs and ther indices
ukeys, index = np.unique(multikeys, return_index=True, axis=0)
# split data columns according to those indices
arrays = np.split(vals, index[1:], axis=1)
# resulting list of subarrays has same number of subarrays as unique key pairs
# each subarray has the following shape:
# rows = number of non-grouped data columns
# cols = number of data points grouped into that unique key pair
# prepare multi index
idx = pd.MultiIndex.from_arrays(ukeys.T, names=col_names)
list_agg_vals = dict()
for tup in zip(*arrays, other_col_names):
col_vals = tup[:-1] # first entries are the subarrays from above
col_name = tup[-1] # last entry is data-column name
list_agg_vals[col_name] = col_vals
df2 = pd.DataFrame(data=list_agg_vals, index=idx)
return df2
测试:
In [227]: %timeit f_multi(df, ['a','d'])
2.54 ms ± 64.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [228]: %timeit df.groupby(['a','d']).agg(list)
4.56 ms ± 61.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
结果:
对于随机种子0,将得到:
要解决一个数据框架的几个列的问题:
In [5]: df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6],'c'
...: :[3,3,3,4,4,4]})
In [6]: df
Out[6]:
a b c
0 A 1 3
1 A 2 3
2 B 5 3
3 B 5 4
4 B 4 4
5 C 6 4
In [7]: df.groupby('a').agg(lambda x: list(x))
Out[7]:
b c
a
A [1, 2] [3, 3]
B [5, 5, 4] [3, 4, 4]
C [6] [4]
这个答案的灵感来自Anamika Modi的回答。谢谢你!
如果在分组多个列时寻找一个唯一的列表,这可能会有所帮助:
df.groupby('a').agg(lambda x: list(set(x))).reset_index()
我发现的实现同样的事情的最简单的方法(至少对于一列)与Anamika的答案类似,只是使用了聚合函数的tuple语法。
df.groupby('a').agg(b=('b','unique'), c=('c','unique'))