Home > OS >  group by 2 columns python
group by 2 columns python

Time:07-21

I have a dataframe of shape :

 id | V
 1    0
 2    1
 3    0
 4    0
 1    0
 2    0
 4    1

where V is only 1 or 0 and id can have duplicates. What i want is for each id to count 0s and 1s. Example above would be

    1 : ('0':2,'1':0)
    4 : ('0':1,'1':1)
    3 : ('0':1,'1':0)
    2 : ('0':1,'1':1)

i don't care about the format of the result this is just an example. It could be a dataframe with 0 and 1 as columnns or whatever.

Any ideas?

CodePudding user response:

You can use the value_counts method.

Example:

df.groupby("id").V.value_counts()

CodePudding user response:

To get the Json format. You can do this.

df.groupby(['id','V'])['V'].count().unstack().T.fillna(0).astype(int).to_json()

Output:

{
  "1":{"0":2,"1":0},
  "2":{"0":1,"1":1},
  "3":{"0":1,"1":0},
  "4":{"0":1,"1":1}
}
  • Related