最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Pandas實現(xiàn)數(shù)據(jù)的清理的入門詳解

 更新時間:2023年08月15日 14:19:11   作者:deephub  
數(shù)據(jù)清理是數(shù)據(jù)分析過程中的關(guān)鍵步驟,它涉及識別缺失值、重復行、異常值和不正確的數(shù)據(jù)類型,本文將介紹6個經(jīng)常使用的數(shù)據(jù)清理操作,希望對大家有所幫助

數(shù)據(jù)清理是數(shù)據(jù)分析過程中的關(guān)鍵步驟,它涉及識別缺失值、重復行、異常值和不正確的數(shù)據(jù)類型。獲得干凈可靠的數(shù)據(jù)對于準確的分析和建模非常重要。

本文將介紹以下6個經(jīng)常使用的數(shù)據(jù)清理操作:

檢查缺失值、檢查重復行、處理離群值、檢查所有列的數(shù)據(jù)類型、刪除不必要的列、數(shù)據(jù)不一致處理

第一步,讓我們導入庫和數(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個缺失值

dropna()

可以刪除包含至少一個缺失值的任何行或列。

# 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)

檢查重復行

duplicate()

方法可以查看重復的行。

# Check duplicate rows
 df.duplicated()
 # Check the number of duplicate rows
 df.duplicated().sum()

drop_duplates()

可以使用這個方法刪除重復的行。

# 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是一個離群值,需要處理

或者還可以繪制直方圖查看數(shù)據(jù)的分布。

plt.figure(figsize=(8, 6))
 df["Product Price"].hist(bins=100)

在直方圖中,可以看到大部分的價格數(shù)據(jù)都在0到500之間。

箱線圖在檢測異常值時也很有用。

plt.figure(figsize=(6, 4))
 df.boxplot(column=['Product Price'])

可以看到價格列有多個離群值數(shù)據(jù)點。(高于400的值)

檢查列的數(shù)據(jù)類型

info()

可以查看數(shù)據(jù)集中列的數(shù)據(jù)類型。

# Provide a summary of dataset
 df.info()

to_datetime()

方法將列轉(zhuǎn)換為日期時間數(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ù)字數(shù)據(jù)類型(例如,整數(shù)或浮點數(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ù)

# 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()

這兩個函數(shù)用于將字符串中的所有字符轉(zhuǎ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)建一個字典,將不一致的值映射到標準化的對應(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的列或索引標簽。

# 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ù),刪除重復的數(shù)據(jù),并有效地執(zhí)行其他數(shù)據(jù)清理操作。

使用pandas功能,數(shù)據(jù)科學家和數(shù)據(jù)分析師可以簡化數(shù)據(jù)清理工作流程,并確保數(shù)據(jù)集的質(zhì)量和完整性。

到此這篇關(guān)于使用Pandas實現(xiàn)數(shù)據(jù)的清理的入門詳解的文章就介紹到這了,更多相關(guān)Pandas數(shù)據(jù)清理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • pip和pygal的安裝實例教程

    pip和pygal的安裝實例教程

    這篇文章主要介紹了pip和pygal的安裝實例教程,具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12
  • 通過實例解析python描述符原理作用

    通過實例解析python描述符原理作用

    這篇文章主要介紹了通過實例解析python描述符原理作用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-01-01
  • Matplotlib實戰(zhàn)之面積圖繪制詳解

    Matplotlib實戰(zhàn)之面積圖繪制詳解

    面積圖,或稱區(qū)域圖,是一種隨有序變量的變化,反映數(shù)值變化的統(tǒng)計圖表,這篇文章主要介紹了如何利用Matplotlib實現(xiàn)面積圖的繪制,需要的可以參考下
    2023-08-08
  • 基于Python制作一個端午節(jié)相關(guān)的小游戲

    基于Python制作一個端午節(jié)相關(guān)的小游戲

    端午節(jié)快樂,今天我將為大家?guī)硪黄嘘P(guān)端午節(jié)的編程文章,希望能夠為大家獻上一份小小的驚喜,我們將會使用Python來實現(xiàn)一個與端午粽子相關(guān)的小應(yīng)用程序,在本文中,我將會介紹如何用Python代碼制做一個“粽子拆解器”,感興趣的小伙伴歡迎閱讀
    2023-06-06
  • python機器學習高數(shù)篇之泰勒公式

    python機器學習高數(shù)篇之泰勒公式

    這篇文章主要介紹了python機器學習高數(shù)篇之函數(shù)極限和導數(shù),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-08-08
  • Python找出列表中出現(xiàn)次數(shù)最多的元素三種方式

    Python找出列表中出現(xiàn)次數(shù)最多的元素三種方式

    本文通過三種方式給大家介紹Python找出列表中出現(xiàn)次數(shù)最多的元素,每種方式通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友參考下
    2020-02-02
  • 常用的Python代碼調(diào)試工具總結(jié)

    常用的Python代碼調(diào)試工具總結(jié)

    今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著Python代碼調(diào)試工具展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • Python requests庫輕松發(fā)送HTTP請求的終極指南

    Python requests庫輕松發(fā)送HTTP請求的終極指南

    在現(xiàn)代網(wǎng)絡(luò)編程中,HTTP請求是與Web服務(wù)交互的基礎(chǔ),本文將全面介紹requests庫的使用方法,從基礎(chǔ)請求到高級技巧,幫助你掌握網(wǎng)絡(luò)數(shù)據(jù)交互的核心技能
    2025-08-08
  • PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換)

    PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換)

    本文主要介紹了PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • 跟老齊學Python之集合的關(guān)系

    跟老齊學Python之集合的關(guān)系

    前面一節(jié)講述了集合的基本概念,注意,那里所涉及到的集合都是可原處修改的集合。還有一種集合,不能在原處修改。
    2014-09-09

最新評論

佳木斯市| 托克逊县| 论坛| 陈巴尔虎旗| 布拖县| 神池县| 杭锦后旗| 青浦区| 凤城市| 静乐县| 赫章县| 吴川市| 铁岭县| 札达县| 景德镇市| 通许县| 顺义区| 沅江市| 永清县| 乐业县| 松原市| 隆昌县| 砀山县| 易门县| 祁门县| 绵阳市| 卢龙县| 滨海县| 治多县| 磐安县| 定日县| 中阳县| 霍山县| 临武县| 广东省| 长阳| 都昌县| 福泉市| 寿阳县| 凌源市| 溧水县|