在Pandas中,如何计算给定另一列值的列值的相对概率?

时间:2017-10-30 07:31:38

标签: python pandas

我有两个数据框vehiclescasualties,每个数据框都有一个公共列Accident_Index

import pandas as pd

vehicles = pd.DataFrame({'Accident_Index': [1, 1, 2, 3, 3, 4, 4], 
                         'Vehicle_Type': ['car', 'car', 'motorcyle', 'car', 'car', 'car', 'car'],
                         'Sex_Driver': ['male', 'female', 'male', 'female', 'female', 'male', 'male']})

casualties = pd.DataFrame({'Accident_Index': [1, 1, 2, 3, 4],
                           'Casualty_Severity': ['fatal', 'serious', 'fatal', 'light', 'fatal']})

为便于可视化,这里是vehicles

   Accident_Index Sex_Driver Vehicle_Type
0               1       male          car
1               1     female          car
2               2       male    motorcyle
3               3     female          car
4               3     female          car
5               4       male          car
6               4       male          car

这里是casualties

   Accident_Index Casualty_Severity
0               1             fatal
1               1           serious
2               2             fatal
3               3             light
4               4             fatal

我想计算一下,与涉及女性汽车司机的事故相比,涉及男性汽车驾驶员的事故致死的次数是多少倍。

到目前为止,我已经提出了以下解决方案:

dfm = casualties.merge(vehicles, on='Accident_Index')
dfm_cars = dfm.loc[dfm.Vehicle_Type == 'car']

dfm_cars_fatal_male = dfm_cars.isin({'Casualty_Severity': ['fatal'], 'Sex_Driver': ['male']})
male_driver_involved_in_fatal_car_accident = (dfm_cars_fatal_male['Casualty_Severity'] & dfm_cars_fatal_male['Sex_Driver']).sum()

dfm_cars_fatal_female = dfm_cars.isin({'Casualty_Severity': ['fatal'], 'Sex_Driver': ['female']})
female_driver_involved_in_fatal_car_accident = (dfm_cars_fatal_female['Casualty_Severity'] & dfm_cars_fatal_female['Sex_Driver']).sum()

print(male_driver_involved_in_fatal_car_accident / female_driver_involved_in_fatal_car_accident)

在这种情况下,答案是3,因为有两起车祸死亡,一起涉及男性和一位女性司机,一起涉及两名男性司机。

然而,这段代码似乎并不是特别简洁。我怎么能重构这个?

1 个答案:

答案 0 :(得分:1)

IIUC,您可以使用merge + query + groupby

g = casualties.merge(vehicles, on='Accident_Index')\
        .query("Vehicle_Type == 'car' and Casualty_Severity == 'fatal'")\
        .groupby('Sex_Driver').Sex_Driver.count()

g / g.sum()

Sex_Driver
female    0.25
male      0.75
Name: Sex_Driver, dtype: float64

为了简化这一点,您可以使用变量进行查询:

vehicle = 'car'
severity = 'fatal'

然后,您可以将query步骤重写为:

query("Vehicle_Type == @vehicle and Casualty_Severity == @severity")

这样可以更容易地重用代码,如果你想把它放在一个函数中并针对各种输入组合进行测试。