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

标签 python pandas pandas-groupby

我在将 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

最佳答案

groupbyjoin结合使用

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/

相关文章:

python - 对 pandas 中具有重复索引的数据框应用滚动平均函数

python - Pandas groupby 得到总和的过滤总和

python - 成功安装PIL,也出现ImportError : cannot import name 'imread' from 'scipy.misc'

python - 使用 Django 1.9 和 Solr 6.1 创建索引时出现日期数学字符串中的无效日期错误

python - 使用 Pandas 进行文本翻译

python - Pandas MultiIndex 按分类顺序自定义排序级别,而不是按字母顺序

python - 检查列中的值是否是另一个数组的超集

python - 如何聚合group by并在出现某个值后丢弃行?

python - 如何调用 'from x import *',其中 x 是 Python 中的变量

python - 您可以使用雅虎财经 API 使用 pandas 提取当前或过去的股息数据吗?