gpt4 book ai didi

pandas - pandas 中的 Groupby 求和与除法

转载 作者:行者123 更新时间:2023-12-02 09:05:04 25 4
gpt4 key购买 nike

我有一个 df,如下所示:

Place       Occupancy     Number
Bangalore Occupied 80
Bangalore Vacant 20
Chennai Occupied 90
Chennai Vacant 60
Delhi Occupied 20
Delhi Vacant 20

我正在尝试生成以下内容:

Place         Occupancy_%     Total_Number   Number_vacant  Number_occupied
Bangalore 80 100 20 80
Chennai 60 150 60 90
Bangalore 50 40 20 20

最佳答案

你可以这样做:

new_df = df.pivot(index='Place', columns='Occupancy', values='Number')
new_df['Total_Number'] = new_df.sum(1)
new_df['Occupancy_%'] = new_df['Occupied']/new_df['Total_Number'] * 100

输出:

Occupancy  Occupied  Vacant  Total_Number  Occupancy_%
Place
Bangalore 80 20 100 80.0
Chennai 90 60 150 60.0
Delhi 20 20 40 50.0

关于pandas - pandas 中的 Groupby 求和与除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59533560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com