python – Pandas使用groupby中的count来创建新列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python – Pandas使用groupby中的count来创建新列相关的知识,希望对你有一定的参考价值。

参考技术A 转自: https://stackoverflow.com/questions/29836477/pandas-create-new-column-with-count-from-groupby

一个看起来如下的df:

我正在尝试创建一个看起来像这样的df:

我努力了

            df["count"] = df.groupby("item")["color"].transform('count')

但它并不是我所寻找的.

任何指导表示赞赏

这不是一个新专栏,这是一个新的DataFrame:

要获得所需的结果,请使用reset_index:

要获得“新列”,您可以使用transform:

Python、Pandas:GroupBy 属性文档

【中文标题】Python、Pandas:GroupBy 属性文档【英文标题】:Python, Pandas: GroupBy attributes documentation 【发布时间】:2017-06-01 08:35:54 【问题描述】:

在 Groupby 文档中,在页面的该级别: http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-object-attributes

如果您向下滚动一点,您会看到它们是所有可用 groupby 属性的列表:

gb.agg        gb.boxplot    gb.cummin     gb.describe   gb.filter     gb.get_group  gb.height     gb.last       gb.median     gb.ngroups    gb.plot       gb.rank       gb.std        gb.transform
gb.aggregate  gb.count      gb.cumprod    gb.dtype      gb.first      gb.groups     gb.hist       gb.max        gb.min        gb.nth        gb.prod       gb.resample   gb.sum        gb.var
gb.apply      gb.cummax     gb.cumsum     gb.fillna     gb.gender     gb.head       gb.indices    gb.mean       gb.name       gb.ohlc       gb.quantile   gb.size       gb.tail       gb.weight

我在哪里可以找到有关这些属性是/做什么的文档?在 Jupyter 中使用 ? 不会显示他们的文档。

【问题讨论】:

我想你可以查一下docs 我想他们都在这里:pandas.pydata.org/pandas-docs/version/0.19.2/api.html#id35 AFAIK,您需要分两步完成。首先将分组对象分配给一个变量,比如gb。然后在 Jupyter 中执行 gb.<attr>? 顺便说一下,在文档中(从这里获取这篇文章)有这个DF 有列(身高/体重/性别)。所以,我猜这些会被当作属性。 @Radar:在 Jupyter 中,输入gb.agg?(例如)后单击“运行单元格”按钮会显示帮助文档字符串。 【参考方案1】:

我想你可以查看groupby docs。

    Indexing, iteration Function application Computations / Descriptive Stats

【讨论】:

【参考方案2】:

您还可以在此处找到有关属性的文档: https://pandas.pydata.org/pandas-docs/stable/reference/groupby.html

【讨论】:

【参考方案3】:

您可以在此link 找到所有说明。 具体来说,左侧菜单中GroupBy 选项卡的子部分。

【讨论】:

以上是关于python – Pandas使用groupby中的count来创建新列的主要内容,如果未能解决你的问题,请参考以下文章

在 python pandas 中使用 groupby 的列中出现的百分比

如果在 groupby 中出现条件,则 Python (Pandas)

python pandas:groupby中2个日期之间的差异

Python Pandas GroupBy 获取组列表

Python pandas:替换 groupby 对象中的选择值

在 Python Pandas 中使用 cumsum 和 groupby 并在值为 0 时重置 cumsum