使用Pandas實(shí)現(xiàn)數(shù)據(jù)的清理的入門詳解
數(shù)據(jù)清理是數(shù)據(jù)分析過程中的關(guān)鍵步驟,它涉及識(shí)別缺失值、重復(fù)行、異常值和不正確的數(shù)據(jù)類型。獲得干凈可靠的數(shù)據(jù)對(duì)于準(zhǔn)確的分析和建模非常重要。
本文將介紹以下6個(gè)經(jīng)常使用的數(shù)據(jù)清理操作:
檢查缺失值、檢查重復(fù)行、處理離群值、檢查所有列的數(shù)據(jù)類型、刪除不必要的列、數(shù)據(jù)不一致處理
第一步,讓我們導(dǎo)入庫(kù)和數(shù)據(jù)集。
# Import libraries import pandas as pd # Read data from a CSV file df = pd.read_csv('filename.csv')
檢查缺失值
isnull()
方法可以用于查看數(shù)據(jù)框或列中的缺失值。
# Check for missing values in the dataframe df.isnull() # Check the number of missing values in the dataframe df.isnull().sum().sort_values(ascending=False)
# Check for missing values in the 'Customer Zipcode' column df['Customer Zipcode'].isnull().sum() # Check what percentage of the data frame these 3 missing values ??represent print(f"3 missing values represents {(df['Customer Zipcode'].isnull().sum() / df.shape[0] * 100).round(4)}% of the rows in our DataFrame.")
Zipcode列中有3個(gè)缺失值
dropna()
可以刪除包含至少一個(gè)缺失值的任何行或列。
# Drop all the rows where at least one element is missing df = df.dropna() # or df.dropna(axis=0) **(axis=0 for rows and axis=1 for columns) # Note: inplace=True modifies the DataFrame rather than creating a new one df.dropna(inplace=True) # Drop all the columns where at least one element is missing df.dropna(axis=1, inplace=True) # Drop rows with missing values in specific columns df.dropna(subset = ['Additional Order items', 'Customer Zipcode'], inplace=True)
fillna()
也可以用更合適的值替換缺失的值,例如平均值、中位數(shù)或自定義值。
# Fill missing values in the dataset with a specific value df = df.fillna(0) # Replace missing values in the dataset with median df = df.fillna(df.median()) # Replace missing values in Order Quantity column with the mean of Order Quantities df['Order Quantity'].fillna(df["Order Quantity"].mean, inplace=True)
檢查重復(fù)行
duplicate()
方法可以查看重復(fù)的行。
# Check duplicate rows df.duplicated() # Check the number of duplicate rows df.duplicated().sum()
drop_duplates()
可以使用這個(gè)方法刪除重復(fù)的行。
# Drop duplicate rows (but only keep the first row) df = df.drop_duplicates(keep='first') #keep='first' / keep='last' / keep=False # Note: inplace=True modifies the DataFrame rather than creating a new one df.drop_duplicates(keep='first', inplace=True)
處理離群值
異常值是可以顯著影響分析的極端值??梢酝ㄟ^刪除它們或?qū)⑺鼈冝D(zhuǎn)換為更合適的值來處理它們。
describe()
的maximum和mean之類的信息可以幫助我們查找離群值。
# Get a statistics summary of the dataset df["Product Price"].describe()
max”值:1999。其他數(shù)值都不接近1999年,而平均值是146,所以可以確定1999是一個(gè)離群值,需要處理
或者還可以繪制直方圖查看數(shù)據(jù)的分布。
plt.figure(figsize=(8, 6)) df["Product Price"].hist(bins=100)
在直方圖中,可以看到大部分的價(jià)格數(shù)據(jù)都在0到500之間。
箱線圖在檢測(cè)異常值時(shí)也很有用。
plt.figure(figsize=(6, 4)) df.boxplot(column=['Product Price'])
可以看到價(jià)格列有多個(gè)離群值數(shù)據(jù)點(diǎn)。(高于400的值)
檢查列的數(shù)據(jù)類型
info()
可以查看數(shù)據(jù)集中列的數(shù)據(jù)類型。
# Provide a summary of dataset df.info()
to_datetime()
方法將列轉(zhuǎn)換為日期時(shí)間數(shù)據(jù)類型。
# Convert data type of Order Date column to date df["Order Date"] = pd.to_datetime(df["Order Date"])
to_numeric()
可以將列轉(zhuǎn)換為數(shù)字?jǐn)?shù)據(jù)類型(例如,整數(shù)或浮點(diǎn)數(shù))。
# Convert data type of Order Quantity column to numeric data type df["Order Quantity"] = pd.to_numeric(df["Order Quantity"])
to_timedelta()
方法將列轉(zhuǎn)換為timedelta數(shù)據(jù)類型,如果值表示持續(xù)時(shí)間,可以使用這個(gè)函數(shù)
# Convert data type of Duration column to timedelta type df["Duration "] = pd.to_timedelta(df["Duration"])
刪除不必要的列
drop()
方法用于從數(shù)據(jù)框中刪除指定的行或列。
# Drop Order Region column # (axis=0 for rows and axis=1 for columns) df = df.drop('Order Region', axis=1) # Drop Order Region column without having to reassign df (using inplace=True) df.drop('Order Region', axis=1, inplace=True) # Drop by column number instead of by column label df = df.drop(df.columns[[0, 1, 3]], axis=1) # df.columns is zero-based
數(shù)據(jù)不一致處理
數(shù)據(jù)不一致可能是由于格式或單位不同造成的。Pandas提供字符串方法來處理不一致的數(shù)據(jù)。
str.lower() & str.upper()
這兩個(gè)函數(shù)用于將字符串中的所有字符轉(zhuǎn)換為小寫或大寫。它有助于標(biāo)準(zhǔn)化DataFrame列中字符串的情況。
# Rename column names to lowercase df.columns = df.columns.str.lower()
# Rename values in Customer Fname column to uppercase df["Customer Fname"] = df["Customer Fname"].str.upper()
str.strip()
函數(shù)用于刪除字符串值開頭或結(jié)尾可能出現(xiàn)的任何額外空格。
# In Customer Segment column, convert names to lowercase and remove leading/trailing spaces df['Customer Segment'] = df['Customer Segment'].str.lower().str.strip()
replace()
函數(shù)用于用新值替換DataFrame列中的特定值。
# Replace values in dataset df = df.replace({"CA": "California", "TX": "Texas"})
# Replace values in a spesific column df["Customer Country"] = df["Customer Country"].replace({"United States": "USA", "Puerto Rico": "PR"})
mapping()
可以創(chuàng)建一個(gè)字典,將不一致的值映射到標(biāo)準(zhǔn)化的對(duì)應(yīng)值。然后將此字典與replace()函數(shù)一起使用以執(zhí)行替換。
# Replace specific values using mapping mapping = {'CA': 'California', 'TX': 'Texas'} df['Customer State'] = df['Customer State'].replace(mapping)
rename()
函數(shù)用于重命名DataFrame的列或索引標(biāo)簽。
# Rename some columns df.rename(columns={'Customer City': 'Customer_City', 'Customer Fname' : 'Customer_Fname'}, inplace=True) # Rename some columns new_names = {'Customer Fname':'Customer_Firstname', 'Customer Fname':'Customer_Fname'} df.rename(columns=new_names, inplace=True) df.head()
總結(jié)
Python pandas包含了豐富的函數(shù)和方法集來處理丟失的數(shù)據(jù),刪除重復(fù)的數(shù)據(jù),并有效地執(zhí)行其他數(shù)據(jù)清理操作。
使用pandas功能,數(shù)據(jù)科學(xué)家和數(shù)據(jù)分析師可以簡(jiǎn)化數(shù)據(jù)清理工作流程,并確保數(shù)據(jù)集的質(zhì)量和完整性。
到此這篇關(guān)于使用Pandas實(shí)現(xiàn)數(shù)據(jù)的清理的入門詳解的文章就介紹到這了,更多相關(guān)Pandas數(shù)據(jù)清理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python單元測(cè)試框架unittest簡(jiǎn)明使用實(shí)例
這篇文章主要介紹了Python單元測(cè)試框架unittest簡(jiǎn)明使用實(shí)例,本文講解了基本測(cè)試步驟、和測(cè)試實(shí)例,需要的朋友可以參考下2015-04-04使用actor-critic方法來控制CartPole-V0 游戲詳解
這篇文章主要為大家介紹了使用actor-critic方法來控制CartPole-V0 游戲詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04Python-pandas返回重復(fù)數(shù)據(jù)的index問題
這篇文章主要介紹了Python-pandas返回重復(fù)數(shù)據(jù)的index問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02Python實(shí)現(xiàn)的密碼強(qiáng)度檢測(cè)器示例
這篇文章主要介紹了Python實(shí)現(xiàn)的密碼強(qiáng)度檢測(cè)器,結(jié)合實(shí)例形式分析了Python密碼強(qiáng)度檢測(cè)的原理與實(shí)現(xiàn)方法,涉及Python字符串運(yùn)算與轉(zhuǎn)換、判斷等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08python tkinter之頂層菜單、彈出菜單實(shí)例
這篇文章主要介紹了python tkinter之頂層菜單、彈出菜單實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03Python DBM模塊輕松使用小型數(shù)據(jù)庫(kù)存儲(chǔ)管理數(shù)據(jù)
這篇文章主要介紹了Python DBM模塊輕松使用小型數(shù)據(jù)庫(kù)存儲(chǔ)管理數(shù)據(jù),它可以讓你輕松地存儲(chǔ)和管理鍵值對(duì)數(shù)據(jù),可以使用 dbm 模塊來操作 DBM 文件,或者使用 shelve 模塊來存儲(chǔ)任意類型的 Python 對(duì)象2024-01-01對(duì)python3 urllib包與http包的使用詳解
今天小編就為大家分享一篇對(duì)python3 urllib包與http包的使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05