What is the best way to count different values ​​in a Dataframe and group by another column?

I have a simple Dataframe that looks like this:

    DRUNK_DR    state
11418   0   Indiana
2129    0   California
17876   0   Nebraska
26033   0   Tennessee
25278   0   South Carolina
10565   0   Illinois
30017   0   Vermont
19079   1   New Mexico
21159   0   North Carolina
22620   0   Oklahoma

DRUNK_DR may be 0 1 2 3

(drunk['DRUNK_DR'].unique()
array([1, 0, 2, 3]))

I would like to get a separate number and group as of state.

Example:

Alabama
0 12121
1 234
2 33
3 9

What is the best way to do this? I tried the following:

drunk.groupby(['state', 'DRUNK_DR']).count()

Does not work:

state   DRUNK_DR
Alabama 0
        1
        2
+4
source share
1 answer

You need to value_counts():

df.groupby('state').DRUNK_DR.value_counts()

#state           DRUNK_DR
#California      0           1
#Illinois        0           1
#Indiana         0           1
#Nebraska        0           1
#New Mexico      1           1
#North Carolina  0           1
#Oklahoma        0           1
#South Carolina  0           1
#Tennessee       0           1
#Vermont         0           1
#Name: DRUNK_DR, dtype: int64
+4
source

Source: https://habr.com/ru/post/1662084/


All Articles