我有一个Pandas数据帧,我正在尝试根据列值对行进行分组,并将一些行合并到列表中。请允许我详细说明:
我拥有的数据帧如下所示:
industry index entities
cars 0 ['Norway', 'it']
cars 0 ['Mercedes', 'they']
cars 0 ['it', 'EV', 'its']
nature 1 ['fox', 'it']
nature 1 ['them', 'rabbits']
nature 2 ['whale', 'it']
所需的数据帧应如下所示:
industry index entities
cars 0 [ ['Norway', 'it'], ['Mercedes', 'they'], ['it', 'EV', 'its'] ]
nature 1 [ ['fox', 'it'], ['them', 'rabbits'] ]
nature 2 ['whale', 'it']
我基本上是根据行业和索引对行进行分组,同时将列entities
的值合并到列表中。你知道吗
我做过这样的尝试
df.groupby('industry')['index'].apply(list)
但是他们给了我完全不同的结果。你知道吗
我怎样才能完成我想要的?非常感谢。你知道吗
您需要在
groupby
之后将index
更改为entities
,以处理列entities
,并在groupby
语句中按list
-['industry','index']进行分组:如果需要不在嵌套列表中的最后一个值,因为通过
if-else
使用lambda函数,每个组只能有一个值:编辑:
如果列
entities
中只有列表的字符串表示,则可以在上述解决方案之前通过ast
模块将值转换为列表:假设
entities
中的元素是list
:输出:
相关问题 更多 >
编程相关推荐