(Python) 如何将列中的唯一值与另一列的总计分组

(Python) How to group unique values in column with total of another column

这是我的数据框的示例:

company_name country_code state_code software finance commerce etc......
google       USA           CA          1        0          0
jimmy        GBR           unknown     0        0          1

我希望能够根据州代码对公司的行业进行分组。例如,我想知道某个州的软件公司总数等(例如,加利福尼亚州有 200 家软件公司,纽约州有 100 家金融公司)。

我目前只是计算每个州的公司总数,使用:

 usa_df['state_code'].value_counts()

但我不知道如何对每个州的每种行业的数量进行分组。

df.groupby(['state_code']).agg({'software' : 'sum', 'finance' : 'sum', ...})

这将按 state_code 进行分组,并在每个分组中总结 'software'、'finance' 等的数量。

也可以做一个 pivot_table:

df.pivot_table(index = 'state_code', columns = ['software', 'finance', ...], aggfunc = 'sum')

如果 1 和 0 是每个类别的布尔标志,那么您应该只需要求和。

df[df.country_code == 'USA'].groupby('state_code').sum().reset_index()

#  state_code  commerce  finance  software
#0         CA         0        0         1

这可能对您有帮助:

result_dataframe = dataframe_name.groupby('state_code ').sum()