如何按两个字段分组并将索引设置为两个字段之一。Pandas、Python3

2024-05-29 10:51:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的堆栈溢出,所以任何社区的最佳实践是受欢迎的。你知道吗

#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不起作用,因为我想保留“city”索引。 Groupby的Groupby似乎也不起作用。 任何帮助都将不胜感激。你知道吗

为清晰起见编辑:我希望按“城市”分组并将其用作索引。我希望在数据帧中有'type',而不是在索引中。当前“Type”返回一个值列表,这些值本质上与重复的值相同。你知道吗


Tags: ofcitydftypeurbanridescombogrouped

热门问题