我有以下数据帧:
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
选择的答案建议使用元组,因为列表是有问题的。另一个答案解释了熊猫代码中发生的情况。元组是最好的方法吗?如何在这里应用
印刷品:
编辑:具有
itertools.chain
的解决方案:这应该做到:
相关问题 更多 >
编程相关推荐