亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python:如何對兩列進行分組?

Python:如何對兩列進行分組?

守候你守候我 2022-01-05 10:28:47
我有一個數據框df,其中包含城市人口的工作和年齡信息df    User   City     Job             Age0    A      x    Unemployed         331    B      x     Student           182    C      x    Unemployed         273    D      y  Data Scientist       284    E      y    Unemployed         455    F      y     Student           18對于每個城市,我想計算失業率和年齡中位數。對于失業率,我做了以下工作## Count the people in each citycust = insDataRed.groupby(['City'])['User'].count() ## Number of people for each citycust = pd.DataFrame(cust)cust.columns=['nCust']cust['City']=cust.indexcust=cust.reset_index(drop=True)## Count the people unemployed in each cityunempl = df[df['Job'] == 'Unemployed']unempl = unempl.groupby(['City'])['Job'].count()unempl = pd.DataFrame(unempl)unempl.columns=['unempl']unempl['City']=unempl.indexunempl=unempl.reset_index(drop=True)# 1. Fraction of UnemploymentunRate = pd.merge(unempl, cust, on = 'City')unRate['rate'] =(unRate['unempl']/unRate['nCust'])*100有沒有更優雅的解決方案?如何計算每個城市的年齡中值?
查看完整描述

1 回答

?
撒科打諢

TA貢獻1934條經驗 獲得超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


查看完整回答
反對 回復 2022-01-05
  • 1 回答
  • 0 關注
  • 292 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號