【问题标题】:How to groupby two fields and set index as one of the two fields. Pandas, Python-3如何对两个字段进行分组并将索引设置为两个字段之一。熊猫,Python-3
【发布时间】:2019-01-03 19:12:40
【问题描述】:

我是 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' 所在的列。或者让 'Type' 显示为不带括号的单个字符串(例如 'Urban')。

df.set_index = False 不起作用,因为我想保留“城市”索引。 groupby 的 Groupby 似乎也不起作用。 任何帮助将不胜感激。

为清楚起见进行编辑:我希望按“城市”分组并将其用作索引。我想在数据框中而不是索引中有“类型”。当前,“类型”返回一个值列表,这些值基本上是重复的相同值。

【问题讨论】:

  • df.reset_index(level=1) 从索引中删除该级别。
  • 你的问题不是很清楚,但我想你需要 groupby 和年龄和 reset_index。像,combo_df.groupby(['city','type']).agg({'fare': 'mean', 'ride_id': 'count'}).reset_index()
  • combo_grouped_df.reset_index(level=1) 给出错误 `Cannot access callable attribute 'reset_index' of 'DataFrameGroupBy' objects, try using the 'apply' method`
  • 在你的聚合函数之后应用它,而不是在第二条评论中指出的分组对象。
  • combo_df.groupby(['city','type']).agg({'fare': 'mean', 'ride_id': 'count'}).reset_index(level=1) 工作。谢谢!

标签: python python-3.x pandas group-by


【解决方案1】:

你只需要:

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) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2015-06-23
    • 2016-05-03
    • 2015-06-17
    • 1970-01-01
    • 2013-02-21
    • 2018-05-19
    相关资源
    最近更新 更多