我在将 R 代码示例转换为我的脚本时遇到问题,并且想知道如何实现相同的目标。
product_df <- example_df[,paste(name, collapse="_"),by=product_id]
我在之前的一个 SO 问题上找到了这个代码片段,但它只是将所有内容连接在一起,而不是通过特定的 ID。
import functools
def reduce_concat(x, sep=""):
return functools.reduce(lambda x, y: str(x) + sep + str(y), x)
def paste(*lists, sep=" ", collapse=None):
result = map(lambda x: reduce_concat(x, sep=sep), zip(*lists))
if collapse is not None:
return reduce_concat(result, sep=collapse)
return list(result)
这是生成下面原始数据框的代码
example_df = pd.DataFrame({'product_id': ['100_1244', '100_1244', '100_1244', '100_1244', '200_1244', '200_1244', '200_1244', '200_1244'],
'name': ['apple', 'apple', 'apple', 'apple', 'orange', 'orange', 'orange', 'orange']})
product_id name
0 100_1244 apple
1 100_1244 apple
2 100_1244 apple
3 100_1244 apple
4 200_1244 orange
5 200_1244 orange
6 200_1244 orange
7 200_1244 orange
我希望它看起来像这样:
product_id name
0 100_1244 apple_apple_apple_apple
1 200_1244 orange_orange_orange_orange
最佳答案
将groupby
与join
结合使用
df.groupby('product_id').apply(lambda x: '_'.join(x['name']))
product_id
100_1244 apple_apple_apple_apple
200_1244 orange_orange_orange_orange
关于python - 如何在 Python 中粘贴(如 R)和 groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54085278/