使用Pandas进行数据清理的入门示例

大数据 数据分析
数据清理是数据分析过程中的关键步骤,它涉及识别缺失值、重复行、异常值和不正确的数据类型。获得干净可靠的数据对于准确的分析和建模非常重要。

数据清理是数据分析过程中的关键步骤,它涉及识别缺失值、重复行、异常值和不正确的数据类型。获得干净可靠的数据对于准确的分析和建模非常重要。

本文将介绍以下6个经常使用的数据清理操作:

检查缺失值、检查重复行、处理离群值、检查所有列的数据类型、删除不必要的列、数据不一致处理

第一步,让我们导入库和数据集。

 # Import libraries
 import pandas as pd
 
 # Read data from a CSV file
 df = pd.read_csv('filename.csv')

检查缺失值

isnull()方法可以用于查看数据框或列中的缺失值。

# 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()也可以用更合适的值替换缺失的值,例如平均值、中位数或自定义值。

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

处理离群值

异常值是可以显著影响分析的极端值。可以通过删除它们或将它们转换为更合适的值来处理它们。

describe()的maximum和mean之类的信息可以帮助我们查找离群值。

# Get a statistics summary of the dataset
 df["Product Price"].describe()

max”值:1999。其他数值都不接近1999年,而平均值是146,所以可以确定1999是一个离群值,需要处理

或者还可以绘制直方图查看数据的分布。

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

在直方图中,可以看到大部分的价格数据都在0到500之间。

箱线图在检测异常值时也很有用。

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

可以看到价格列有多个离群值数据点。(高于400的值)

检查列的数据类型

info()可以查看数据集中列的数据类型。

# Provide a summary of dataset 
df.info()

to_datetime()方法将列转换为日期时间数据类型。

 # Convert data type of Order Date column to date
 df["Order Date"] = pd.to_datetime(df["Order Date"])

to_numeric()可以将列转换为数字数据类型(例如,整数或浮点数)。

 # Convert data type of Order Quantity column to numeric data type
 df["Order Quantity"] = pd.to_numeric(df["Order Quantity"])

to_timedelta()方法将列转换为timedelta数据类型,如果值表示持续时间,可以使用这个函数

 # Convert data type of Duration column to timedelta type
 df["Duration "] = pd.to_timedelta(df["Duration"])

删除不必要的列

drop()方法用于从数据框中删除指定的行或列。

 # 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

数据不一致处理

数据不一致可能是由于格式或单位不同造成的。Pandas提供字符串方法来处理不一致的数据。

str.lower() & str.upper()这两个函数用于将字符串中的所有字符转换为小写或大写。它有助于标准化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()函数用于删除字符串值开头或结尾可能出现的任何额外空格。

# In Customer Segment column, convert names to lowercase and remove leading/trailing spaces
 df['Customer Segment'] = df['Customer Segment'].str.lower().str.strip()

replace()函数用于用新值替换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()可以创建一个字典,将不一致的值映射到标准化的对应值。然后将此字典与replace()函数一起使用以执行替换。

 # Replace specific values using mapping
 mapping = {'CA': 'California', 'TX': 'Texas'}
 df['Customer State'] = df['Customer State'].replace(mapping)

rename()函数用于重命名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()

总结

Python pandas包含了丰富的函数和方法集来处理丢失的数据,删除重复的数据,并有效地执行其他数据清理操作。

使用pandas功能,数据科学家和数据分析师可以简化数据清理工作流程,并确保数据集的质量和完整性。

责任编辑:华轩 来源: DeepHub IMBA
相关推荐

2023-02-15 08:24:12

数据分析数据可视化

2023-09-26 01:03:36

Pandas数据数据集

2018-04-03 12:07:53

数据清洗PandasNumpy

2020-06-05 14:29:07

PythonPandas数据分析

2017-10-31 11:55:46

sklearn数据挖掘自动化

2020-12-14 13:24:17

PandasSQL数据集

2017-02-16 08:41:09

数据Vlookup匹配

2022-08-02 09:32:47

pandas移动计算

2019-09-30 10:12:21

机器学习数据映射

2009-09-08 16:50:12

使用LINQ进行数据转

2009-03-16 10:29:45

数据挖掘过滤器Access

2022-11-02 14:45:24

Python数据分析工具

2022-03-28 14:08:02

Python数据清洗数据集

2009-07-16 14:46:48

jdbc statem

2022-04-08 11:25:58

数据库操作AbilityData

2021-12-27 09:50:03

JavaScript开发数据分组

2020-08-14 10:45:26

Pandas可视化数据预处理

2021-03-11 10:48:33

机器学习数据清理

2011-10-14 14:24:26

Ruby

2023-10-18 18:38:44

数据校验业务
点赞
收藏

51CTO技术栈公众号