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

如何基于userid列合并多行文本记录

按userid分组合并Input字段内容的实现方案

原始数据

Input                     userid
hello                      1001  
hi                         1002  
my name is bill            1002  
how are you?               1003  
can you help?              1003  
what is new?               1005  
hello                      1006  
about my request           1006

需求目标

基于userid列对Input字段内容分组,将同一userid对应的所有Input文本用空格拼接,得到如下结果:

Input                      userid
hello                       1001  
hi my name is bill          1002  
how are you? can you help?  1003              
what is new?                1005  
hello about my request      1006

实现方法

1. Python Pandas(推荐数据处理场景)

利用Pandas分组聚合功能快速实现:

import pandas as pd

# 构造数据(从文件读取可替换为pd.read_csv('your_file.csv'))
data = {
    'Input': ['hello', 'hi', 'my name is bill', 'how are you?', 'can you help?', 'what is new?', 'hello', 'about my request'],
    'userid': [1001, 1002, 1002, 1003, 1003, 1005, 1006, 1006]
}
df = pd.DataFrame(data)

# 分组拼接Input字段
result = df.groupby('userid')['Input'].apply(' '.join).reset_index()

# 输出结果
print(result)

2. SQL(适用于数据库存储的数据)

不同数据库的字符串聚合函数略有差异:

  • MySQL/MariaDB:
SELECT 
  GROUP_CONCAT(Input SEPARATOR ' ') AS Input,
  userid
FROM your_table
GROUP BY userid;
  • PostgreSQL:
SELECT 
  STRING_AGG(Input, ' ') AS Input,
  userid
FROM your_table
GROUP BY userid;
  • SQL Server(2017+):
SELECT 
  STRING_AGG(Input, ' ') AS Input,
  userid
FROM your_table
GROUP BY userid;

3. Shell Awk(适用于纯文本文件)

如果数据是空格/制表符分隔的文本文件,可直接用Awk处理:

# 假设数据以制表符分隔,若为空格需调整分隔符逻辑
awk -F'\t' '{
  if (input[$2] == "") input[$2] = $1
  else input[$2] = input[$2] " " $1
}
END {
  for (id in input) printf "%-30s %d\n", input[id], id
}' your_data.txt

内容的提问来源于stack exchange,提问作者Tal1992

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:22:48