清理與存取資料

在 Python 中處理類別資料

Kasey Jones

Research Data Scientist

類別資料的常見問題

1) 不一致值:"Ham""ham"" Ham"

2) 拼字錯誤:"Ham""Hma"

3) 錯誤的 dtypedf['Our Column'].dtype

dtype('O')
在 Python 中處理類別資料

找出問題

使用以下任一方法:

  • Series.cat.categories
  • Series.value_counts()
dogs["get_along_cats"].value_counts()
No     2503
yes     275
no      156
Noo       2
 NO       1
在 Python 中處理類別資料

修正問題:空白字元

移除空白:.strip()

dogs["get_along_cats"] = dogs["get_along_cats"].str.strip()

檢查次數分佈:

dogs["get_along_cats"].value_counts()
No     2503
yes     275
no      156
Noo       2
NO        1   # < ---- 沒有多餘空白了
在 Python 中處理類別資料

修正問題:大小寫

大小寫:.title().upper().lower()

dogs["get_along_cats"] = dogs["get_along_cats"].str.title()

檢查次數分佈:

dogs["get_along_cats"].value_counts()
No     2660 
Yes     275
Noo       2
在 Python 中處理類別資料

修正問題:拼字錯誤

.replace() 修正錯字

replace_map = {"Noo": "No"}
dogs["get_along_cats"].replace(replace_map, inplace=True)

檢查次數分佈:

dogs["get_along_cats"].value_counts()
No     2662
Yes     275
在 Python 中處理類別資料

檢查資料型別

檢查 dtype

dogs["get_along_cats"].dtype
dtype('O')

轉回類別型別

dogs["get_along_cats"] = dogs["get_along_cats"].astype("category")
在 Python 中處理類別資料

使用 str 存取器物件

搜尋字串

dogs["breed"].str.contains("Shepherd", regex=False)
0        False
1        False
2        False
...
2935     False
2936     True
在 Python 中處理類別資料

用 loc 存取資料

依類別存取 Series 值

dogs.loc[dogs["get_along_cats"] == "Yes", "size"]

Series 計數:

dogs.loc[dogs["get_along_cats"] == "Yes", "size"].value_counts(sort=False)
small      69
medium    169
large      37
在 Python 中處理類別資料

清理與存取:練習

在 Python 中處理類別資料

Preparing Video For Download...