Python:如何对两列进行分组?

时间:2019-04-09 15:30:50

标签: python pandas group-by

我有一个数据框df,其中包含城市工作人员和年龄的信息

df
    User   City     Job             Age
0    A      x    Unemployed         33
1    B      x     Student           18
2    C      x    Unemployed         27
3    D      y  Data Scientist       28
4    E      y    Unemployed         45
5    F      y     Student           18

我想为每个城市计算失业率和年龄中位数。

对于失业率,我做了以下事情

## Count the people in each city
cust = insDataRed.groupby(['City'])['User'].count() ## Number of people for each city
cust = pd.DataFrame(cust)
cust.columns=['nCust']
cust['City']=cust.index
cust=cust.reset_index(drop=True)

## Count the people unemployed in each city
unempl = df[df['Job'] == 'Unemployed']
unempl = unempl.groupby(['City'])['Job'].count()
unempl = pd.DataFrame(unempl)
unempl.columns=['unempl']
unempl['City']=unempl.index
unempl=unempl.reset_index(drop=True)


# 1. Fraction of Unemployment
unRate = pd.merge(unempl, cust, on = 'City')
unRate['rate'] =(unRate['unempl']/unRate['nCust'])*100

有没有更优雅的解决方案?如何计算每个城市的年龄中值?

1 个答案:

答案 0 :(得分:2)

如果您只想在纽约市这样做:

df.groupby(by='City').median()

如果您要按城市和工作分组:

df.groupby(by=['City', 'Job']).median()

获取每个城市的失业率:

import pandas as pd

df = pd.DataFrame({
    'User': ['A', 'B', 'C', 'D', 'E', 'F'], 'City': ['x', 'x', 'x', 'y', 'y', 'y'], 
    'Job': ['Unemployed', 'Student', 'Unemployed', 'Data Scientist', 'Unemployed', 'Student'],
    'Age':[33, 18, 27, 28, 45, 18],
})

df['count'] = 1
unmpl = df.groupby(by=['City', 'Job'])['count'].sum().reset_index()

unmpl_by_city = unmpl[unmpl['Job'] == 'Unemployed'].reset_index(drop=True)
count_by_city = df.groupby(by=['City'])['count'].sum().reset_index(drop=True)

frac_by_city = (unmpl_by_city['count'] * 100.0 / 
                count_by_city)

unmpl_by_city['frac'] = frac_by_city
unmpl_by_city