在Python中,可以使用pandas库来按某一列分组,并将多个列的唯一字符串值连接成一个单独的列。下面是一个示例代码:
import pandas as pd
# 创建一个示例数据集
data = {'Group': ['A', 'A', 'B', 'B', 'C'],
'Column1': ['Apple', 'Banana', 'Carrot', 'Date', 'Egg'],
'Column2': ['Apple', 'Banana', 'Carrot', 'Date', 'Egg']}
df = pd.DataFrame(data)
# 按Group列分组,并将Column1和Column2的唯一字符串值连接成一个单独的列
df_grouped = df.groupby('Group').agg({'Column1': lambda x: '|'.join(x.unique()),
'Column2': lambda x: '|'.join(x.unique())}).reset_index()
# 打印结果
print(df_grouped)
输出结果:
Group Column1 Column2
0 A Apple|Banana Apple|Banana
1 B Carrot|Date Carrot|Date
2 C Egg Egg
在上面的示例代码中,我们首先创建了一个示例数据集df。然后,使用groupby函数按Group列分组,并使用agg函数将Column1和Column2的唯一字符串值连接成一个单独的列。最后,使用reset_index函数重置索引,并打印结果。
下一篇:按模型计算字段排序记录