如何使用Pandas将DataFrame列值按分组拼接生成新DataFrame
按ProductName分组拼接列值的解决方案
没问题,这个需求用pandas的分组聚合功能就能轻松实现,我给你一步步拆解:
1. 先构造原DataFrame1
首先我们把你给出的原始数据转换成pandas DataFrame:
import pandas as pd data = { 'ProductName': ['Product1', 'Product2', 'Product1', 'Product3', 'Product3', 'Product1', 'Product2'], 'Value': [2, 3, 1, 4, 5, 5, 9], 'otherValue': [5, 2, 5, 7, 7, 5, 2] } df1 = pd.DataFrame(data)
2. 分组聚合生成目标DataFrame2
核心就是用groupby按ProductName分组,然后对不同列用对应的聚合逻辑:
- 对
Value列:把每个组里的数值转成字符串,再用空格拼接起来 - 对
otherValue列:观察你的示例数据,同组内的otherValue值都是一致的,所以直接取组内第一个值就可以(用first、max、min都能达到同样效果)
代码如下:
df2 = df1.groupby('ProductName').agg( Value=('Value', lambda x: ' '.join(map(str, x))), otherValue=('otherValue', 'first') ).reset_index()
3. 查看结果
运行后打印df2就能得到你想要的格式:
print(df2)
输出结果:
ProductName Value otherValue 0 Product1 2 1 5 5 1 Product2 3 9 2 2 Product3 4 5 7
如果你的otherValue组内存在不同值,只需要把聚合逻辑改成和Value一样的拼接方式就行:lambda x: ' '.join(map(str, x))。
内容的提问来源于stack exchange,提问作者goerge
相关产品推荐
相关产品推荐

