掌握 Python 數(shù)據(jù)清洗的七個(gè)必備技巧
數(shù)據(jù)清洗是在數(shù)據(jù)分析和數(shù)據(jù)科學(xué)項(xiàng)目中的一個(gè)關(guān)鍵環(huán)節(jié)。很多小伙伴可能會(huì)覺得它枯燥,但實(shí)際上,掌握好數(shù)據(jù)清洗的技巧能大大提高效率。今天,我們就來聊聊Python數(shù)據(jù)清洗的七個(gè)必備技巧。
技巧一:去除重復(fù)值
首先,我們先從簡單的一環(huán)開始——去除重復(fù)值。想象一下,你的數(shù)據(jù)中有些行可能是完全一樣的,這在分析時(shí)會(huì)影響準(zhǔn)確性。
示例代碼:
import pandas as pd
# 創(chuàng)建一個(gè)示例數(shù)據(jù)框
data = {'name': ['Tom', 'Jerry', 'Mike', 'Tom'],
'age': [25, 30, 40, 25]}
df = pd.DataFrame(data)
print("原始數(shù)據(jù):")
print(df)
# 使用drop_duplicates方法刪除重復(fù)行
df_cleaned = df.drop_duplicates()
print("\n去重后的數(shù)據(jù):")
print(df_cleaned)
解釋:這里drop_duplicates()函數(shù)用來移除DataFrame中的重復(fù)行。
技巧二:缺失值處理
數(shù)據(jù)中的空值是非常常見的問題,我們可以選擇刪除或填充這些缺失值。
示例代碼:
# 在原數(shù)據(jù)幀基礎(chǔ)上添加一些缺失值
df_missing = df_cleaned.copy()
df_missing.loc[1, 'age'] = None
print("帶缺失值的數(shù)據(jù):")
print(df_missing)
# 刪除包含空值的行
df_dropped = df_missing.dropna()
print("\n刪除含空值的行后:")
print(df_dropped)
# 或者用均值填充空值
mean_age = df['age'].mean()
df_filled = df_missing.fillna(mean_age)
print("\n用平均值填充后的數(shù)據(jù):")
print(df_filled)
技巧三:文本數(shù)據(jù)清洗
當(dāng)我們的數(shù)據(jù)涉及大量文本時(shí),需要進(jìn)行清理以便更好地分析,比如轉(zhuǎn)換大小寫、移除空格等。
示例代碼:
text_data = {'text': [' Python ', ' JAVA ', 'c++']}
df_text = pd.DataFrame(text_data)
# 去除空格,并統(tǒng)一轉(zhuǎn)換為小寫
df_text['text'] = df_text['text'].str.strip().str.lower()
print("清理后的文本數(shù)據(jù):")
print(df_text)
技巧四:數(shù)據(jù)類型轉(zhuǎn)換
確保每一列的數(shù)據(jù)都是正確的類型對(duì)于后續(xù)操作是重要的。
示例代碼:
# 轉(zhuǎn)換年齡列為整數(shù)類型
df_dropped['age'] = df_dropped['age'].astype('int')
print("轉(zhuǎn)換數(shù)據(jù)類型的后:")
print(df_dropped.dtypes)
技巧五:離群值檢測(cè)與處理
有時(shí)候,異常高或低的數(shù)值也被稱為離群值。它們可能影響模型的結(jié)果。
示例代碼:
from scipy import stats
data_with_outliers = [25, 30, 40, 25, 200]
z_scores = stats.zscore(data_with_outliers)
filtered_data = [d for d, z in zip(data_with_outliers, z_scores) if abs(z) < 2]
print("去除離群值后的數(shù)據(jù):", filtered_data)
技巧六:日期時(shí)間處理
日期和時(shí)間信息常需標(biāo)準(zhǔn)化以方便計(jì)算和分析。
示例代碼:
date_series = pd.Series(['2023-1-3', '2023/1/4', None])
cleaned_dates = pd.to_datetime(date_series, errors='coerce')
print("處理后的時(shí)間數(shù)據(jù):")
print(cleaned_dates)
技巧七:合并多個(gè)表
當(dāng)你有多份數(shù)據(jù)表時(shí),如何將他們組合在一起是關(guān)鍵。
示例代碼:
df1 = pd.DataFrame({'key': ['A', 'B', 'C'], 'data': [1, 2, 3]})
df2 = pd.DataFrame({'key': ['B', 'C', 'D'], 'info': ['x', 'y', 'z']})
merged_df = pd.merge(df1, df2, on='key', how='inner')
print("合并后的數(shù)據(jù):")
print(merged_df)
實(shí)戰(zhàn)案例
假如你現(xiàn)在負(fù)責(zé)一家電商平臺(tái)的數(shù)據(jù)分析工作,需要處理用戶購買行為記錄的數(shù)據(jù)集。你需要先清理數(shù)據(jù),包括去重、處理丟失值,接著分析用戶最常購買的類別等??梢試L試?yán)媒裉鞂W(xué)到的技術(shù)點(diǎn)逐一解決問題。