python - 如何对两个字段进行分组并将索引设置为两个字段之一。熊猫,Python-3
问题描述
我是 Stack Overflow 的新手,所以也欢迎任何社区最佳实践。
#aggregate rides and average of fares
combo_grouped_df =combo_df.groupby(['city','type'])
#combo_grouped_df.set_index('city') does not work!
combo_grouped_df.head()
avg_fare =combo_grouped_df['fare'].mean()
total_rides =combo_grouped_df['ride_id'].count()
city_type = combo_grouped_df['type']
summary_df = pd.DataFrame({"Average Fare": avg_fare,
"Number of Rides": total_rides,
"Type": combo_grouped_df['type']}) # how to get type in this dict?????
summary_df.head()}
结果是:
Average Fare Number of Rides \
city type
Amandaburgh Urban 24.641667 18
Barajasview Urban 25.332273 22
Barronchester Suburban 36.422500 16
Bethanyland Suburban 32.956111 18
Bradshawfurt Rural 40.064000 10
Type
city type
Amandaburgh Urban ((Amandaburgh, Urban), [Urban, Urban, Urban, U...
Barajasview Urban ((Barajasview, Urban), [Urban, Urban, Urban, U...
Barronchester Suburban ((Barronchester, Suburban), [Suburban, Suburba...
Bethanyland Suburban ((Bethanyland, Suburban), [Suburban, Suburban,...
Bradshawfurt Rural ((Bradshawfurt, Rural), [Rural, Rural, Rural, ...
我想将 goupby 'type' 索引移动到 'Type' 所在的列。或者让“类型”显示为不带括号的单个字符串(例如“城市”)。
df.set_index = False
不起作用,因为我想保留“城市”索引。groupby 的 Groupby 似乎也不起作用。任何帮助,将不胜感激。
为清楚起见进行编辑:我希望按“城市”分组并将其用作索引。我想在数据框中而不是索引中有“类型”。当前,“类型”返回一个值列表,这些值基本上是重复的相同值。
解决方案
所有你需要的是:
import pandas as pd
# Group it
group_df = combo_df.groupby(['city','type'])
# Aggregate it
aggregated_df = group_df.agg({'fare': 'mean', 'ride_id': 'count'})
# Reset index (only type)
summary_df = aggregated_df.reset_index(level=1)
推荐阅读
- openssl - 生成多个具有相同模数的 RSA 密钥
- java - 是什么导致了这个 ArchUnit 异常?
- arangodb - Arango commitIntervalMsec 和solidationIntervalMsec 以减少等待时间
- java - mongoTemplate executeCommand 错误:未授权
- c# - 设置可以注入的填充对象的最佳方法是什么?
- apache-flink - Flink 流式传输:全局窗口何时开始?
- java - Firebase Cloud Storage Java Admin SDK 使用 contentType 上传文件
- oauth-2.0 - 如何在金字塔框架中启用谷歌身份验证?
- vuejs3 - Vue3 将 html 添加到现有项目
- javascript - jest-each 是否提供了一种方法来更多地访问测试描述中传递的参数?