[英]How to group identical values and count their frequency in Python?
我有一個包含 2 列的 dataframe
source_number category
222 cat2
123 cat4
111 cat1
321 cat3
543 cat1
542 cat4
333 cat1
343 cat2
我根據 Amiga500 的答案編輯function我運行以下代碼:
s = df["category"].value_counts()
print(s)
cat1 1
cat1 2
cat2 1
cat2 1
cat3 1
cat4 2
cat1 3
cat2 2
cat3 1
cat4 2
此語句中的錯誤在哪里以及如何解決?
看起來您的列中有一些whitespaces
。 嘗試使用str.strip()
刪除前導和尾隨字符(包括空格):
df['category'].value_counts()
Out[364]:
cat4 2
cat1 2
cat2 1
cat3 1
cat2 1
cat1 1
# With using str.strip()
df['category'].str.strip().value_counts()
Out[365]:
cat1 3
cat2 2
cat4 2
cat3 1
這個?
df['cat'].value_counts()
編輯:
基於上面現在介紹的 dataframe,代碼應為:
df['category'].value_counts()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.