Python Pandas: 通过除以 2 个数组求百分比

Python Pandas: Find percentage by dividing 2 arrays

我有一个数据框,我拉出 2 条数据(各州警察杀人,各州警察杀黑人):

import pandas as pd

police_df = pd.read_csv("police.csv")
print(police_df['state'].value_counts())
print((police_df.loc[police_df['race'] == 'B'])['state'].value_counts())

我想知道每个州的谋杀案中黑人占多少百分比。我假设我会通过将 2 个数组按每个元素明智地划分来做到这一点。我该怎么做?

考虑示例数据框 police_df

police_df = pd.DataFrame(dict(
        state='s1 s1 s1 s1 s2 s2 s2 s2 s3 s3 s3'.split(),
        race=list('BOBOOOOBBBB')
    ))

print(police_df)

   race state
0     B    s1
1     O    s1
2     B    s1
3     O    s1
4     O    s2
5     O    s2
6     O    s2
7     B    s2
8     B    s3
9     B    s3
10    B    s3

使用 groupbyvalue_countsnormalize=True

police_df.groupby('state').race.value_counts(normalize=True).unstack(fill_value=0)

race      B     O
state            
s1     0.50  0.50
s2     0.25  0.75
s3     1.00  0.00