简体   繁体   中英

Count unique values in multiple columns according by group (pandas dataframe)

I have a dataframe in pandas:

    a  b  c  d  e
0   1  x  y  t  u
1   1  x  z  y  v
2   1  y  x  t  z
3   2  x  t  z  u
4   2  z  x  y  t 
5   3  x  z  y  t

I need to transform this dataframe into this:

   a  x  y  z  t  u  v  y  z
0  1  3  3  2  2  1  1  3  2
1  2  2  1  2  2  1  0  1  2
2  3  1  1  1  1  0  0  0  0

IIUC

df.set_index('a').stack().groupby(level=0).value_counts().unstack(fill_value=0)
Out[514]: 
   t  u  v  x  y  z
a                  
1  2  1  1  3  3  2
2  2  1  0  2  1  2
3  1  0  0  1  1  1

Or using melt + crosstab

s=df.melt('a')
pd.crosstab(s.a,s.value)
Out[518]: 
value  t  u  v  x  y  z
a                      
1      2  1  1  3  3  2
2      2  1  0  2  1  2
3      1  0  0  1  1  1
df.melt(id_vars="a").groupby(["a","value"]).count().unstack().fillna(0)

      variable                         
value        t    u    v    x    y    z
a                                      
1          2.0  1.0  1.0  3.0  3.0  2.0
2          2.0  1.0  0.0  2.0  1.0  2.0
3          1.0  0.0  0.0  1.0  1.0  1.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM