网站开发流程博客,域名网站如何做,淄博网站营销与推广,网站在百度的图标显示不正常数据清理是数据分析过程中的关键步骤#xff0c;它涉及识别缺失值、重复行、异常值和不正确的数据类型。获得干净可靠的数据对于准确的分析和建模非常重要。 本文将介绍以下6个经常使用的数据清理操作#xff1a;
检查缺失值、检查重复行、处理离群值、检查所有列的数据类型…数据清理是数据分析过程中的关键步骤它涉及识别缺失值、重复行、异常值和不正确的数据类型。获得干净可靠的数据对于准确的分析和建模非常重要。 本文将介绍以下6个经常使用的数据清理操作
检查缺失值、检查重复行、处理离群值、检查所有列的数据类型、删除不必要的列、数据不一致处理
第一步让我们导入库和数据集。 # Import librariesimport pandas as pd# Read data from a CSV filedf pd.read_csv(filename.csv)检查缺失值
isnull()方法可以用于查看数据框或列中的缺失值。 # Check for missing values in the dataframedf.isnull()# Check the number of missing values in the dataframedf.isnull().sum().sort_values(ascendingFalse)# Check for missing values in the Customer Zipcode columndf[Customer Zipcode].isnull().sum()# Check what percentage of the data frame these 3 missing values ••representprint(f3 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 missingdf df.dropna() # or df.dropna(axis0) **(axis0 for rows and axis1 for columns)# Note: inplaceTrue modifies the DataFrame rather than creating a new onedf.dropna(inplaceTrue)# Drop all the columns where at least one element is missingdf.dropna(axis1, inplaceTrue)# Drop rows with missing values in specific columnsdf.dropna(subset [Additional Order items, Customer Zipcode], inplaceTrue)fillna()也可以用更合适的值替换缺失的值例如平均值、中位数或自定义值。 # Fill missing values in the dataset with a specific valuedf df.fillna(0)# Replace missing values in the dataset with mediandf df.fillna(df.median())# Replace missing values in Order Quantity column with the mean of Order Quantitiesdf[Order Quantity].fillna(df[Order Quantity].mean, inplaceTrue)检查重复行
duplicate()方法可以查看重复的行。 # Check duplicate rowsdf.duplicated()# Check the number of duplicate rowsdf.duplicated().sum()drop_duplates()可以使用这个方法删除重复的行。 # Drop duplicate rows (but only keep the first row)df df.drop_duplicates(keepfirst) #keepfirst / keeplast / keepFalse# Note: inplaceTrue modifies the DataFrame rather than creating a new onedf.drop_duplicates(keepfirst, inplaceTrue)处理离群值
异常值是可以显著影响分析的极端值。可以通过删除它们或将它们转换为更合适的值来处理它们。
describe()的maximum和mean之类的信息可以帮助我们查找离群值。 # Get a statistics summary of the datasetdf[Product Price].describe()max”值:1999。其他数值都不接近1999年而平均值是146所以可以确定1999是一个离群值需要处理
或者还可以绘制直方图查看数据的分布。 plt.figure(figsize(8, 6))df[Product Price].hist(bins100)在直方图中可以看到大部分的价格数据都在0到500之间。
箱线图在检测异常值时也很有用。 plt.figure(figsize(6, 4))df.boxplot(column[Product Price])可以看到价格列有多个离群值数据点。(高于400的值)
检查列的数据类型
info()可以查看数据集中列的数据类型。 # Provide a summary of datasetdf.info()to_datetime()方法将列转换为日期时间数据类型。 # Convert data type of Order Date column to datedf[Order Date] pd.to_datetime(df[Order Date])to_numeric()可以将列转换为数字数据类型(例如整数或浮点数)。 # Convert data type of Order Quantity column to numeric data typedf[Order Quantity] pd.to_numeric(df[Order Quantity])to_timedelta()方法将列转换为timedelta数据类型如果值表示持续时间可以使用这个函数 # Convert data type of Duration column to timedelta typedf[Duration ] pd.to_timedelta(df[Duration])删除不必要的列
drop()方法用于从数据框中删除指定的行或列。 # Drop Order Region column# (axis0 for rows and axis1 for columns)df df.drop(Order Region, axis1)# Drop Order Region column without having to reassign df (using inplaceTrue)df.drop(Order Region, axis1, inplaceTrue)# Drop by column number instead of by column labeldf df.drop(df.columns[[0, 1, 3]], axis1) # df.columns is zero-based数据不一致处理
数据不一致可能是由于格式或单位不同造成的。Pandas提供字符串方法来处理不一致的数据。
str.lower() str.upper()这两个函数用于将字符串中的所有字符转换为小写或大写。它有助于标准化DataFrame列中字符串的情况。 # Rename column names to lowercasedf.columns df.columns.str.lower()# Rename values in Customer Fname column to uppercasedf[Customer Fname] df[Customer Fname].str.upper()str.strip()函数用于删除字符串值开头或结尾可能出现的任何额外空格。 # In Customer Segment column, convert names to lowercase and remove leading/trailing spacesdf[Customer Segment] df[Customer Segment].str.lower().str.strip()replace()函数用于用新值替换DataFrame列中的特定值。 # Replace values in datasetdf df.replace({CA: California, TX: Texas})# Replace values in a spesific columndf[Customer Country] df[Customer Country].replace({United States: USA, Puerto Rico: PR})mapping()可以创建一个字典将不一致的值映射到标准化的对应值。然后将此字典与replace()函数一起使用以执行替换。 # Replace specific values using mappingmapping {CA: California, TX: Texas}df[Customer State] df[Customer State].replace(mapping)rename()函数用于重命名DataFrame的列或索引标签。 # Rename some columnsdf.rename(columns{Customer City: Customer_City, Customer Fname : Customer_Fname}, inplaceTrue)# Rename some columnsnew_names {Customer Fname:Customer_Firstname, Customer Fname:Customer_Fname}df.rename(columnsnew_names, inplaceTrue)df.head()总结
Python pandas包含了丰富的函数和方法集来处理丢失的数据删除重复的数据并有效地执行其他数据清理操作。
使用pandas功能数据科学家和数据分析师可以简化数据清理工作流程并确保数据集的质量和完整性。
https://avoid.overfit.cn/post/d594591441dd47b2b1a6264c1c71368a
作者Python Fundamentals