You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:00:10