【发布时间】:2021-11-05 00:56:05
【问题描述】:
我有一个如下所示的数据框:
dfB
name value country
benzene spice Australia
benzene spice Australia
benzene spice Australia
benzene herbs Australia
benzene herbs Americas
benzene anise Poland
methyl herbs
methyl herbs Americas
methyl spice Americas
alcohol spice Germany
alcohol spice Germany
我想创建一个不同的数据框,它是国家列的聚合,如下所示:
dfB
name value country count
benzene spice Australia 3
benzene herbs Australia 1
benzene herbs Americas 1
benzene anise Poland 1
methyl herbs 1
methyl herbs Americas 1
methyl spice Americas 1
alcohol spice Germany 2
这个想法是聚合国家列并为每个唯一的“名称”和“值”组合创建国家列的计数。如果有空格或楠也应该区别对待。
我尝试使用 groupby:
grouped = dfB.groupby(["name", "value", "country"]).agg({"country": "count"})
但它似乎并没有按照我的意图创建数据框。我该怎么做?
【问题讨论】:
-
从 groupby 中删除“国家”,或者使用
nunique代替agg -
如果有空格或 Nan,他也应该区别对待。 - 如果说 3 NaN - 它们应该算作 3 还是 1?跨度>
-
检查第二个重复的答案。
-
如果相同的“名称”“值”组合有3个Nan/Blanks,则应计为1。
-
使用
dfB.groupby(["name", "value", "country"]).size().reset_index(name='count')
标签: python pandas dataframe pandas-groupby aggregation