การทำความสะอาดและการเข้าถึงข้อมูล

การทำงานกับข้อมูลเชิงกลุ่มใน Python

Kasey Jones

Research Data Scientist

ปัญหาที่อาจพบในข้อมูลเชิงหมวดหมู่

1) ค่าที่ไม่สอดคล้องกัน: "Ham", "ham", " Ham"

2) ค่าที่สะกดผิด: "Ham", "Hma"

3) dtype ที่ไม่ถูกต้อง: df['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   # < ---- no more whitespace
การทำงานกับข้อมูลเชิงกลุ่มใน 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')

แปลงกลับเป็น category

dogs["get_along_cats"] = dogs["get_along_cats"].astype("category")
การทำงานกับข้อมูลเชิงกลุ่มใน Python

การใช้ str accessor object

การค้นหาสตริง

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...