您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Pandas:groupby和可变权重

Pandas:groupby和可变权重

只需将两列相乘:

In [11]: df_city['weighted_jobs'] = df_city['weight'] * df_city['jobs']

现在您可以按城市分组(并取总和):

In [12]: df_city_sums = df_city.groupby('city').sum()

In [13]: df_city_sums
Out[13]: 
           jobs  weight  weighted_jobs
city                                  
oakland     362     690           7958
san mateo   367    1017           9026
sf          253     638           6209

[3 rows x 3 columns]

现在,您可以将两个和除,以获得所需的结果:

In [14]: df_city_sums['weighted_jobs'] / df_city_sums['jobs']
Out[14]: 
city
oakland      21.983425
san mateo    24.594005
sf           24.541502
dtype: float64
其他 2022/1/1 18:44:57 有390人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶