python - 通过 Pandas 中的字符串列聚合数据框
问题描述
我有一个如下所示的数据框:
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"})
但它似乎并没有按照我的意图创建数据框。我怎样才能做到这一点?
解决方案
使用value_counts
或groupby
不修改顺序:
out = dfB.value_counts(["name", "value", "country"], sort=False, dropna=False) \
.rename('count').reset_index()
out.loc[out['country'].isna(), 'count'] = 1
out1 = dfB.groupby(["name", "value", "country"], sort=False, dropna=False) \
.size().reset_index(name='count')
out1.loc[out1['country'].isna(), 'count'] = 1
>>> out
name value country count
0 alcohol spice Germany 2
1 benzene anise Poland 1
2 benzene herbs Americas 1
3 benzene herbs Australia 1
4 benzene spice Australia 3
5 methyl herbs Americas 1
6 methyl herbs NaN 1
7 methyl spice Americas 1
>>> out1
name value country count
0 benzene spice Australia 3
1 benzene herbs Australia 1
2 benzene herbs Americas 1
3 benzene anise Poland 1
4 methyl herbs NaN 1
5 methyl herbs Americas 1
6 methyl spice Americas 1
7 alcohol spice Germany 2
推荐阅读
- php - 在 PHP 中计算大小尺寸
- macos - 须藤、PK 执行等。在 MAC 上不存在
- java - 无法使用 Keycloak 验证应用程序用户的登录
- amazon-web-services - 有没有办法使用 NLB 对 PHP-FPM + NGINX 的 HTTP 请求进行负载平衡?
- ruby-on-rails - Heroku Rails 服务器 API 启动时未设置正确的端口号
- javascript - 如果计算属性 vuejs 中没有任何更改,如何将旧值传递给 setter?
- php - 将整数转换为 PHP 数组中的特定浮点数
- r - 用 R 中的条件(4 个级别)估算数据
- flutter - 未处理的异常:键入“列表”
' 不是类型 'String' 的子类型 - reactjs - 如何在没有反应路由器的情况下创建新页面