Python 如何基于pandas中的多个列进行分组?

Python 如何基于pandas中的多个列进行分组?,python,pandas,group-by,concat,Python,Pandas,Group By,Concat,我想根据基于多列的数据帧进行分组。例如,要做到这一点: Country Type_1 Type_2 Type_3 Type_4 Type_5 China A B C D E Spain A A R B C Italy B A B R R 为此: Country Type Count China A 1

我想根据基于多列的数据帧进行分组。例如,要做到这一点:

Country Type_1 Type_2  Type_3  Type_4  Type_5
China    A       B       C        D      E
Spain    A       A       R        B      C
Italy    B       A       B        R      R
为此:

Country Type   Count
China   A       1
        B       1
        C       1 
        D       1
        E       1
Spain   A       2
        R       1
        B       1
        C       1
Italy   B       2  
        A       1   
        R       2

我尝试将列从类型_1垂直连接到类型_5,应用reset_index(),然后尝试计数。然而,我不知道如何按国家垂直分组。有什么想法吗


Thx

Do
melt
然后
groupby
size

s = df.melt('Country').groupby(['Country','value']).size()
Out[326]: 
Country  value
China    A        1
         B        1
         C        1
         D        1
         E        1
Italy    A        1
         B        2
         R        2
Spain    A        2
         B        1
         C        1
         R        1
dtype: int64

谢谢,这似乎是可行的,但我还想按国家划分眼病类型的数量,而且不适用于melt。可以这样做吗?s=df.melt('Country').groupby(['Country','value']).size().unstack().plot(kind='bar')@MasterC