在Pandas中将列值连接为行值 [英] Concatenating column values into row values in Pandas

查看:72
本文介绍了在Pandas中将列值连接为行值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的数据框-两列都是字符串,而ValCol是由逗号分隔的整数组成的字符串。索引是没有意义的通用整数索引。

I have a dataframe like the below- both columns are strings, with the ValCol being a string of comma separated integers. The index is a generic integer index with no meaning.

NameCol    ValCol
Name1      555, 333
Name2      433
Name1      999
Name3      123
Name2      533

这是什么将其聚合到的最佳方法

What's the best way to aggregate it to

NameCol    ValCol
Name1      555, 333, 999
Name2      433, 533
Name3      123

T不关心逗号分隔整数的顺序,但是我确实需要在它们之间保持逗号。可能会是一个很小的数据框,小于100条记录,因此效率并不重要。

T don't care about the order of the comma separated integers, but I do need to keep commas between them. It likely will be a very small dataframe, <100 records, so efficiency isn't critical.

我觉得应该对此采取某种分组方法,但是我

I feel like there should be some groupby approach to this, but I haven't figured it out yet.

推荐答案

使用 groupby 方法:

df = df.groupby('NameCol')['ValCol'].apply(', '.join).reset_index()

结果输出:

  NameCol         ValCol
0   Name1  555, 333, 999
1   Name2       433, 533
2   Name3            123

这篇关于在Pandas中将列值连接为行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆