Làm sạch dữ liệu với Python
Adel Nehme
Content Developer @DataCamp
I) Không nhất quán giá trị
'married', 'Maried', 'UNMARRIED', 'not married'..'married ', ' married '..II) Gộp quá nhiều hạng mục thành ít
0-20K, 20-40K ... từ dữ liệu thu nhập hộ liên tục'rich', 'poor'III) Đảm bảo kiểu dữ liệu là category (đã xem ở Chương 1)
Chữ hoa/thường: 'married', 'Married', 'UNMARRIED', 'unmarried'..
# Lấy cột tình trạng hôn nhân
marriage_status = demographics['marriage_status']
marriage_status.value_counts()
unmarried 352
married 268
MARRIED 204
UNMARRIED 176
dtype: int64
# Đếm giá trị theo nhóm trong DataFrame
marriage_status.groupby('marriage_status').count()
household_income gender
marriage_status
MARRIED 204 204
UNMARRIED 176 176
married 268 268
unmarried 352 352
# Chuyển thành chữ hoamarriage_status['marriage_status'] = marriage_status['marriage_status'].str.upper() marriage_status['marriage_status'].value_counts()
UNMARRIED 528
MARRIED 472
# Chuyển thành chữ thườngmarriage_status['marriage_status'] = marriage_status['marriage_status'].str.lower() marriage_status['marriage_status'].value_counts()
unmarried 528
married 472
Khoảng trắng thừa: 'married ', 'married', 'unmarried', ' unmarried'..
# Lấy cột tình trạng hôn nhân
marriage_status = demographics['marriage_status']
marriage_status.value_counts()
unmarried 352
unmarried 268
married 204
married 176
dtype: int64
# Loại bỏ mọi khoảng trắng
demographics = demographics['marriage_status'].str.strip()
demographics['marriage_status'].value_counts()
unmarried 528
married 472
Tạo nhóm từ dữ liệu: cột income_group từ cột income.
# Dùng qcut()
import pandas as pd
group_names = ['0-200K', '200K-500K', '500K+']
demographics['income_group'] = pd.qcut(demographics['household_income'], q = 3,
labels = group_names)
# In cột income_group
demographics[['income_group', 'household_income']]
category household_income
0 200K-500K 189243
1 500K+ 778533
..
Tạo nhóm từ dữ liệu: cột income_group từ cột income.
# Dùng cut() - tạo khoảng và tên nhóm
ranges = [0,200000,500000,np.inf]
group_names = ['0-200K', '200K-500K', '500K+']
# Tạo cột nhóm thu nhập
demographics['income_group'] = pd.cut(demographics['household_income'], bins=ranges,
labels=group_names)
demographics[['income_group', 'household_income']]
category Income
0 0-200K 189243
1 500K+ 778533
Gộp nhiều hạng mục thành ít hơn: giảm số hạng mục trong cột phân loại.
Cột operating_system hiện: 'Microsoft', 'MacOS', 'IOS', 'Android', 'Linux'
Cột operating_system cần thành: 'DesktopOS', 'MobileOS'
# Tạo từ điển ánh xạ và thay thế
mapping = {'Microsoft':'DesktopOS', 'MacOS':'DesktopOS', 'Linux':'DesktopOS',
'IOS':'MobileOS', 'Android':'MobileOS'}
devices['operating_system'] = devices['operating_system'].replace(mapping)
devices['operating_system'].unique()
array(['DesktopOS', 'MobileOS'], dtype=object)
Làm sạch dữ liệu với Python