可以使用pandas库中的groupby函数进行分组,然后使用apply函数来实现对每个组进行操作。具体实现过程如下:
import pandas as pd
# 创建示例数据
data = {'id': [1, 1, 2, 2, 3, 3],
'word': ['hello', 'world', 'apple', 'banana', 'cat', 'dog'],
'value': [10, 10, 20, 20, 30, 30]}
df = pd.DataFrame(data)
# 定义函数,把单元格中的单词粘合起来
def concatenate_words(words):
return ' '.join(words)
# 分组并应用函数
result = df.groupby('value')['word'].apply(concatenate_words).reset_index()
# 输出结果
print(result)
输出结果为:
value word
0 10 hello world
1 20 apple banana
2 30 cat dog
其中,id列的值被忽略了,word列的值被合并了,形成了一个新的DataFrame。