Python 如何在groupby中将数据帧行分组到列表中
我有一个熊猫数据帧Python 如何在groupby中将数据帧行分组到列表中,python,pandas,list,aggregate,pandas-groupby,Python,Pandas,List,Aggregate,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执行类似操作?正如您所说的pd的groupby方法。DataFrame对象可以执行此操作 范例 L = ['A','A','B','B','B','C'] N = [1,2,5,5,4,6] import pandas as pd df = pd.Data
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执行类似操作?正如您所说的
pd的groupby
方法。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
您可以使用
groupby
对感兴趣的列进行分组,然后对每个组应用列表
:
In [1]: df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]})
df
Out[1]:
a b
0 A 1
1 A 2
2 B 5
3 B 5
4 B 4
5 C 6
In [2]: df.groupby('a')['b'].apply(list)
Out[2]:
a
A [1, 2]
B [5, 5, 4]
C [6]
Name: b, dtype: object
In [3]: df1 = df.groupby('a')['b'].apply(list).reset_index(name='new')
df1
Out[3]:
a new
0 A [1, 2]
1 B [5, 5, 4]
2 C [6]
如果性能很重要,请转到numpy级别:
测验:
实现这一目标的简便方法是:
df.groupby('a').agg({'b':lambda x: list(x)})
研究如何编写自定义聚合:要解决数据帧中多个列的聚合问题:
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]
这个答案的灵感来源于他的答案。谢谢大家! 让我们将df.groupby
与列表和Series
构造函数一起使用
pd.Series({x : y.b.tolist() for x , y in df.groupby('a')})
Out[664]:
A [1, 2]
B [5, 5, 4]
C [6]
dtype: object
使用以下任一groupby
和agg
配方
# Setup
df = pd.DataFrame({
'a': ['A', 'A', 'B', 'B', 'B', 'C'],
'b': [1, 2, 5, 5, 4, 6],
'c': ['x', 'y', 'z', 'x', 'y', 'z']
})
df
a b c
0 A 1 x
1 A 2 y
2 B 5 z
3 B 5 x
4 B 4 y
5 C 6 z
要将多个列聚合为列表,请使用以下任一选项:
df.groupby('a').agg(list)
df.groupby('a').agg(pd.Series.tolist)
b c
a
A [1, 2] [x, y]
B [5, 5, 4] [z, x, y]
C [6] [z]
要仅对单个列进行分组列表,请将groupby转换为SeriesGroupBy
对象,然后调用SeriesGroupBy.agg
。使用
df.groupby('a').agg({'b': list}) # 4.42 ms
df.groupby('a')['b'].agg(list) # 2.76 ms - faster
a
A [1, 2]
B [5, 5, 4]
C [6]
Name: b, dtype: object
这里,我用“|”作为分隔符对元素进行分组
import pandas as pd
df = pd.read_csv('input.csv')
df
Out[1]:
Area Keywords
0 A 1
1 A 2
2 B 5
3 B 5
4 B 4
5 C 6
df.dropna(inplace = True)
df['Area']=df['Area'].apply(lambda x:x.lower().strip())
print df.columns
df_op = df.groupby('Area').agg({"Keywords":lambda x : "|".join(x)})
df_op.to_csv('output.csv')
Out[2]:
df_op
Area Keywords
A [1| 2]
B [5| 5| 4]
C [6]
如果在分组多个列时查找唯一的列表,这可能会有所帮助:
df.groupby('a').agg(lambda x: list(set(x))).reset_index()
现在是使用agg
而不是apply
的时候了
什么时候
若要将多个列堆叠到列表中,则会产生pd.DataFrame
df.groupby('a')[['b', 'c']].agg(list)
# or
df.groupby('a').agg(list)
如果希望列表中只有一列,则生成ps.Series
df.groupby('a')['b'].agg(list)
#or
df.groupby('a')['b'].apply(list)
请注意,当您仅聚合单个列时,导致pd.DataFrame
比导致ps.Series
的速度慢10倍左右,请在多列情况下使用它。我所看到的最简单的方法是,至少对于一列,无法实现大部分相同的功能,这与聚合函数的元组语法类似
df.groupby('a').agg(b=('b','unique'), c=('c','unique'))
答案基于@EdChum对其答案的评论。评论是这样的吗-
groupby is notoriously slow and memory hungry, what you could do is sort by column A, then find the idxmin and idxmax (probably store this in a dict) and use this to slice your dataframe would be faster I think
让我们首先创建一个dataframe,第一列中有500k个类别,总df shape为2000万,如前面提到的
df = pd.DataFrame(columns=['a', 'b'])
df['a'] = (np.random.randint(low=0, high=500000, size=(20000000,))).astype(str)
df['b'] = list(range(20000000))
print(df.shape)
df.head()
对于第一列中的2000万行和500万个类别,上述代码需要2分钟。在此基础上,这里是一个更通用的版本,并已更新以与较新的库版本一起使用:(numpy版本1.19.2
,pandas版本1.2.1
)
此解决方案还可以处理多个索引
:
A [1,2]
B [5,5,4]
C [6]
但是,这并没有经过严格测试,请谨慎使用
如果性能很重要,请转到numpy级别:
测验:
结果:
对于随机种子0,将得到:
只是一种补充
pandas.pivot_表
更具通用性,似乎更方便:
“数据”
df=pd.DataFrame({'a':['a','a','B','B','B','C'],
‘b’:[1,2,5,5,4,6],
‘c’:[1,2,1,1,1,6]})
打印(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
“使用数据透视表”
pt=pd.枢轴_表(df,
值=['b','c'],
索引='a',
aggfunc={'b':列表,
“c”:集合})
打印(pt)
b c
A.
A[1,2]{1,2}
B[5,5,4]{1}
C[6]{6}
如果数据集很大,比如说1000万行,这需要很多时间。有没有更快的办法?然而,“a”中的Unique数量大约为500kgroupby是出了名的缓慢和内存不足,您可以做的是按a列排序,然后找到idxmin和idxmax(可能将其存储在dict中),并使用它分割数据帧,我想当我尝试解决我的问题时,会更快(具有多个要分组的列和要分组的列),它不起作用-pandas发送的“函数不减少”。然后我在第二个答案后使用了元组:。请参阅中的第二个答案以获取解释。此解决方案很好,但是否有方法存储列表集,这意味着我可以删除重复项然后存储它?@PoeteMaudit抱歉,我不明白您的要求,请询问注释中的问题在SO中的形式不好。你是在问如何将多个列连接到一个列表中吗?lambda args:f(args)
相当于f
实际上,只是agg(list)
就足够了。另请参见。!!我只是在谷歌上搜索一些语法,意识到我自己的笔记本被引用为解决方案lol。感谢链接此链接。只需添加,由于“list”不是一个系列函数,您必须将其与applydf.groupby('a').apply(list)
一起使用,或者将其与agg一起作为dictdf.groupby的一部分使用('a').agg({'b':list})
。您也可以将其用于lambda(我推荐),因为您可以使用它做更多的事情。例如:df.groupby('a').agg({'c':'first','b':lambda x:x.unique().tolist())
允许您对列c应用一个系列函数,然后对列b应用一个唯一的列表函数。如果我们通过两个或多个键进行分组,例如使用.groupby([df.index.month,df.index.day]),
而不仅仅是.groupby('a'),我们如何使用它
?@ru111我在下面添加了一个您可能想签出的元素。它还处理多列分组。上面的方法保证保持顺序吗?这意味着来自同一行的元素(但不同列,上面代码中的b和c)结果列表中是否会有相同的索引?@Kai oh,问得好。是和否。GroupBy根据grouper键值对输出进行排序。但是排序通常是稳定的,因此每个组的相对顺序会保留。若要完全禁用排序行为,请使用GroupBy(…,sort=False)
。在这里,因为我是groupin,所以没有什么区别
groupby is notoriously slow and memory hungry, what you could do is sort by column A, then find the idxmin and idxmax (probably store this in a dict) and use this to slice your dataframe would be faster I think
df = pd.DataFrame(columns=['a', 'b'])
df['a'] = (np.random.randint(low=0, high=500000, size=(20000000,))).astype(str)
df['b'] = list(range(20000000))
print(df.shape)
df.head()
# Sort data by first column
df.sort_values(by=['a'], ascending=True, inplace=True)
df.reset_index(drop=True, inplace=True)
# Create a temp column
df['temp_idx'] = list(range(df.shape[0]))
# Take all values of b in a separate list
all_values_b = list(df.b.values)
print(len(all_values_b))
# For each category in column a, find min and max indexes
gp_df = df.groupby(['a']).agg({'temp_idx': [np.min, np.max]})
gp_df.reset_index(inplace=True)
gp_df.columns = ['a', 'temp_idx_min', 'temp_idx_max']
# Now create final list_b column, using min and max indexes for each category of a and filtering list of b.
gp_df['list_b'] = gp_df[['temp_idx_min', 'temp_idx_max']].apply(lambda x: all_values_b[x[0]:x[1]+1], axis=1)
print(gp_df.shape)
gp_df.head()
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)