[英]How to split two kind of values in the column and count the number of occurrence?
我想要一個 dataframe 有一個 TRUE 和 FALSE 列。 我想得到一個 dataframe 像:
樣本輸入
Country | Class | Catalog
A | abc | TRUE
A | abc | FALSE
B | def | TRUE
C | ghi | FALSE
樣品 Output
Country | Class | TRUE | FALSE | TOTAL
A | abc | 1 | 1 | 2
B | def | 1 | 0 | 1
C | ghi | 0 | 1 | 1
我試過:
df.groupby(['Country','Class','Country'])['Catalog'].value_counts()
但我沒有得到想要的結果。
有什么幫助嗎?
使用crosstab
並通過DataFrame.iloc
刪除最后一行:
df1 = (pd.crosstab([df['Country'], df['Class']],
df['Catalog'],
margins=True,
margins_name='TOTAL')
.iloc[:-1])
print (df1)
Catalog False True TOTAL
Country Class
A abc 1 1 2
B def 0 1 1
C ghi 1 0 1
您的解決方案應由sum
更改並由Series.unstack
添加由DataFrame.assign
填充的新列:
#removed repeated column in groupby
df1 = (df.groupby(['Country','Class'])['Catalog']
.value_counts()
.unstack(fill_value=0)
.assign(Total = lambda x: x.sum(axis=1)))
print (df1)
Catalog False True Total
Country Class
A abc 1 1 2
B def 0 1 1
C ghi 1 0 1
最后從MultiIndex
添加DataFrame.reset_index
和DataFrame.rename_axis
列:
df1 = df1.reset_index().rename_axis(None, axis=1)
print (df1)
Country Class False True Total
0 A abc 1 1 2
1 B def 0 1 1
2 C ghi 1 0 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.