【发布时间】:2020-10-09 03:06:04
【问题描述】:
我有以下数据框:
df=pd.DataFrame({'code1':["A","B","A"],"code2":["k","l","k"],'Names':[['EUGENIO NETO','JUAN MATIAS SERAGOPIAN'],['EUGENIO LUPORINI NETO'],['SIMONE FANKHAUSER','ALEX SOUZA']]})
code1 code2 Names
0 A k [EUGENIO NETO, JUAN MATIAS SERAGOPIAN]
1 B l [EUGENIO LUPORINI NETO]
2 A k [SIMONE FANKHAUSER, ALEX SOUZA]
我想将code1 和code2 分组并合并Names 中的列表。在某种程度上看起来像这样:
code1 code2 Names
0 A k [EUGENIO NETO, JUAN MATIAS SERAGOPIAN, SIMONE FANKHAUSER, ALEX SOUZA]
1 B l [EUGENIO LUPORINI NETO]
已经检查了以下答案:
Groupby and append lists and strings
所以我尝试根据我的情况调整这些问题的答案(但未能解决):
df['Names']=df[['code1','code2',"Names"]].groupby(['code1','code2'])["Names"].agg('sum')
----> ValueError: Function does not reduce
df['Names']=df[['code1','code2',"Names"]].groupby(['code1','code2'])["Names"].agg('Names')
----> AttributeError: 'SeriesGroupBy' object has no attribute 'Names'
df['Names']=df[['code1','code2',"Names"]].groupby(['code1','code2'])["Names"].transform(lambda x: append(x))
----> NameError: name 'append' is not defined
是我遗漏了什么还是方法不对?
编辑
Andrej 和 NYC Coder 确实提出了功能性解决方案。但是当我在更大的数据集中运行它时,我得到了相同的ValueError: Function does not reduce。研究了这可能是什么,并在这里发现了这个问题:Pandas Groupby Agg Function Does Not Reduce
选择的答案建议使用元组,因为列表是有问题的。另一个答案解释了熊猫代码中发生这种情况的位置。元组将是最好的方式?如何在这里应用?
【问题讨论】:
-
你用的是什么版本的熊猫?
-
@ScottBoston 0.25
标签: python pandas pandas-groupby