如何在 Python 中粘贴(如 R)和 groupby

我无法将 R 代码示例转换为我的脚本,并且想知道如何实现相同的目标。


product_df <- example_df[,paste(name, collapse="_"),by=product_id]

但它只是将所有内容连接在一起,而不是通过特定 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


白板的微信
浏览 295回答 3
3回答

慕无忌7234182

洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情洪水无情

饮歌长啸

你可以检查 groupbyexample_df.groupby('product_id').name.apply('_'.join).reset_index()&nbsp; product_id&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;name0&nbsp; &nbsp;100_1244&nbsp; &nbsp; &nbsp; apple_apple_apple_apple1&nbsp; &nbsp;200_1244&nbsp; orange_orange_orange_orange

千万里不及你

使用groupby与joindf.groupby('product_id').apply(lambda x: '_'.join(x['name']))product_id100_1244&nbsp; &nbsp; &nbsp; &nbsp; apple_apple_apple_apple200_1244&nbsp; &nbsp; orange_orange_orange_orange
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python