[英]How to groupby based on multiple columns in pandas?
我想根據多列按 dataframe 分組。 例如做這個:
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
我嘗試垂直連接從 Type_1 到 Type_5 的列,應用 reset_index() 然后嘗試計數。 但是我不知道如何按國家/地區垂直分組。 有任何想法嗎?
謝謝
melt
然后按size
groupby
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.