Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Data Cleaning

Pandas Data Cleaning

Data cleaning is the process of handling useless data.

Many datasets have missing data, incorrect data formats, erroneous data, or duplicate data. To make data analysis more accurate, such useless data needs to be processed.

Common steps of data cleaning and preprocessing:

  1. Handling Missing Values: Identify and fill missing values, or remove rows/columns containing missing values.

  2. Handling duplicate data: Check and remove duplicate data to ensure each record is unique.

  3. Handling outliers: Identify and handle outliers, such as extreme values and erroneous values.

  4. Data format conversion: Convert data types or perform unit conversion, such as date format conversion.

  5. Standardization and normalization: Standardize (e.g., Z-score) or normalize (e.g., Min-Max) numerical data.

  6. Encoding categorical data: Convert categorical variables to numeric form; common methods include One-Hot encoding and label encoding.

  7. Text processing: Clean text data, such as removing stop words, stemming, tokenization, etc.

  8. Data sampling: Extract samples from the dataset, or handle class imbalance through oversampling/undersampling.

  9. Feature Engineering: Create new features, remove irrelevant features, select important features, etc.

In this tutorial, we will use the Pandas package for data cleaning.

The test data used in this article property-data.csv is as follows:

The table above contains four kinds of empty data:


Pandas cleaning of null values

If we want to remove rows containing empty fields, we can use the dropna() method, with the following syntax:

DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

Parameter Description:

We can use isnull() to determine whether each cell is empty.

Example

import

pandas

as

pd

df

=

pd.

read_csv

(

'property-data.csv'

)

print

(

df

[

'NUM_BEDROOMS'

]

)

print

(

df

[

'NUM_BEDROOMS'

]

.

isnull

(

)

)

The output of the above example is:

In the example above we saw that Pandas treats n/a and NA as empty data, while na is not empty data, which does not meet our requirements; we can specify the null value types:

Example

import

pandas

as

pd

missing_values

=

[

"n/a"

,

"na"

,

"--"

]

df

=

pd.

read_csv

(

'property-data.csv'

,

na_values

=

missing_values

)

print

(

df

[

'NUM_BEDROOMS'

]

)

print

(

df

[

'NUM_BEDROOMS'

]

.

isnull

(

)

)

The output of the above example is:

The following example demonstrates removing rows that contain empty data.

Example

import

pandas

as

pd

df

=

pd.

read_csv

(

'property-data.csv'

)

new_df

=

df.

dropna

(

)

print

(

new_df.

to_string

(

)

)

The output of the above example is:

**Note:** By default, the dropna() method returns a new DataFrame and does not modify the source data.

If you want to modify the source DataFrame, you can use inplace = True Parameters:

Example

import

pandas

as

pd

df

=

pd.

read_csv

(

'property-data.csv'

)

df.

dropna

(

inplace

=

True

)

print

(

df.

to_string

(

)

)

The output of the above example is:

We can also remove rows where a specified column has null values:

Example

Remove rows where the ST_NUM column has an empty field value:

import

pandas

as

pd

df

=

pd.

read_csv

(

'property-data.csv'

)

df.

dropna

(

subset

=

[

'ST_NUM'

]

,

inplace

=

True

)

print

(

df.

to_string

(

)

)

The output of the above example is:

We can also fillna() method to replace some empty fields:

Example

Replace empty fields with 12345:

import

pandas

as

pd

df

=

pd.

read_csv

(

'property-data.csv'

)

df.

fillna

(

12345

,

inplace

=

True

)

print

(

df.

to_string

(

)

)

The output of the above example is:

We can also specify a column to replace data in:

Example

Replace null data in PID with 12345:

import

pandas

as

pd

df

=

pd.

read_csv

(

'property-data.csv'

)

df

[

'PID'

]

.

fillna

(

12345

,

inplace

=

True

)

print

(

df.

to_string

(

)

)

The output of the above example is:

A common method for replacing empty cells is to compute the column's mean, median, or mode.

Pandas uses the mean(), median(), and mode() methods to compute a column's mean (the average of all values), median (the middle number after sorting), and mode (the most frequent number).

Example

Use the mean() method to compute a column's mean and replace empty cells:

import

pandas

as

pd

df

=

pd.

read_csv

(

'property-data.csv'

)

x

=

df

[

"ST_NUM"

]

.

mean

(

)

df

[

"ST_NUM"

]

.

fillna

(

x

,

inplace

=

True

)

print

(

df.

to_string

(

)

)

The output of the example above is shown below; the red box indicates the mean used to replace the empty cells:

Example

Use the median() method to compute a column's median and replace empty cells:

import

pandas

as

pd

df

=

pd.

read_csv

(

'property-data.csv'

)

x

=

df

[

"ST_NUM"

]

.

median

(

)

df

[

"ST_NUM"

]

.

fillna

(

x

,

inplace

=

True

)

print

(

df.

to_string

(

)

)

The output of the example above is shown below; the red box indicates the median used to replace the empty cells:

Example

Use the mode() method to compute a column's mode and replace empty cells:

import

pandas

as

pd

df

=

pd.

read_csv

(

'property-data.csv'

)

x

=

df

[

"ST_NUM"

]

.

mode

(

)

df

[

"ST_NUM"

]

.

fillna

(

x

,

inplace

=

True

)

print

(

df.

to_string

(

)

)

The output of the example above is shown below; the red box indicates the mode used to replace the empty cells:


Pandas cleaning of incorrectly formatted data

Cells with incorrect data formats make data analysis difficult or even impossible.

We can do this by including rows with empty cells, or by converting all cells in a column to data of the same format.

The following example formats dates:

Example

import

pandas

as

pd

The third date has an incorrect format

data

=

{

 

"Date"

:

[

'2020/12/01'

,

'2020/12/02'

,

'20201226'

]

,

 

"duration"

:

[

50

,

40

,

45

]

}

df

=

pd.

DataFrame

(

data

,

index

=

[

"day1"

,

"day2"

,

"day3"

]

)

df

[

'Date'

]

=

pd.

to_datetime

(

df

[

'Date'

]

,

format

=

'mixed'

)

print

(

df.

to_string

(

)

)

The output of the above example is:



           Date  duration

day1 2020-12-01        50

day2 2020-12-02        40

day3 2020-12-26        45


Pandas cleaning of erroneous data

Data errors are also common; we can replace or remove erroneous data.

The following example replaces erroneous age data:

Example

import

pandas

as

pd

person

=

{

 

"name"

:

[

'Google'

,

'Runoob'

,

'Taobao'

]

,

 

"age"

:

[

50

,

40

,

12345

]

   

The age value 12345 is erroneous

}

df

=

pd.

DataFrame

(

person

)

df.

loc

[

2

,

'age'

]

=

30

Update data

print

(

df.

to_string

(

)

)

The output of the above example is:



     name  age

0  Google   50

1  Runoob   40

2  Taobao   30

You can also set a conditional statement:

Example

Set age greater than 120 to 120:

import

pandas

as

pd

person

=

{

 

"name"

:

[

'Google'

,

'Runoob'

,

'Taobao'

]

,

 

"age"

:

[

50

,

200

,

12345

]

   

}

df

=

pd.

DataFrame

(

person

)

for

x

in

df.

index

:

 

if

df.

loc

[

x

,

"age"

]

120

:

    df.

loc

[

x

,

"age"

]

=

120

print

(

df.

to_string

(

)

)

The output of the above example is:



     name  age

0  Google   50

1  Runoob  120

2  Taobao  120

You can also delete rows with erroneous data:

Example

Delete rows where age is greater than 120:

import

pandas

as

pd

person

=

{

 

"name"

:

[

'Google'

,

'Runoob'

,

'Taobao'

]

,

 

"age"

:

[

50

,

40

,

12345

]

   

The age value 12345 is erroneous

}

df

=

pd.

DataFrame

(

person

)

for

x

in

df.

index

:

 

if

df.

loc

[

x

,

"age"

]

120

:

    df.

drop

(

x

,

inplace

=

True

)

print

(

df.

to_string

(

)

)

The output of the above example is:



     name  age

0  Google   50

1  Runoob   40


Pandas cleaning of duplicate data

If we want to clean duplicate data, we can use duplicated() and drop_duplicates() method.

If the corresponding data is duplicated,duplicated() will return True, otherwise False.

Example

import

pandas

as

pd

person

=

{

 

"name"

:

[

'Google'

,

'Runoob'

,

'Runoob'

,

'Taobao'

]

,

 

"age"

:

[

50

,

40

,

40

,

23

]

 

}

df

=

pd.

DataFrame

(

person

)

print

(

df.

duplicated

(

)

)

The output of the above example is:



0    False

1    False

2     True

3    False

dtype: bool

To delete duplicate data, you can directly usedrop_duplicates() method.

Example

import

pandas

as

pd

persons

=

{

 

"name"

:

[

'Google'

,

'Runoob'

,

'Runoob'

,

'Taobao'

]

,

 

"age"

:

[

50

,

40

,

40

,

23

]

 

}

df

=

pd.

DataFrame

(

persons

)

df.

drop_duplicates

(

inplace

=

True

)

print

(

df

)

The output of the above example is:



     name  age

0  Google   50

1  Runoob   40

3  Taobao   23

Common methods and descriptions

Common methods of data cleaning and preprocessing:

Operation Method/step Description Common functions/methods
Handling Missing Values Fill missing values Fill missing values with a specified value (such as mean, median, mode, etc.). df.fillna(value)
Delete missing values Remove rows or columns containing missing values. df.dropna()
Handling duplicate data Remove duplicate data Remove duplicate rows in a DataFrame. df.drop_duplicates()
Handling outliers Outlier detection (based on statistical methods) Identify and handle outliers via Z-score or IQR methods. Custom functions (such as those based on Z-score or IQR)
Replace outliers Replace outliers with appropriate values (such as the mean or median). Custom functions (such as functions that replace outliers)
Data format conversion Converting Data Types Convert a data type from one type to another, such as converting a string to a date. df.astype()
Datetime format conversion Convert strings or numbers to datetime type. pd.to_datetime()
Standardization and normalization Standardization Transform data to a distribution with mean 0 and standard deviation 1. StandardScaler()
Normalization Scale data to a specified range (such as [0, 1]). MinMaxScaler()
Encoding categorical data Label Encoding Convert categorical variables to integer form. LabelEncoder()
One-Hot Encoding Convert each category into a new binary feature. pd.get_dummies()
Text data processing Remove stop words Remove insignificant words from text, such as "the", "is", etc. Custom functions (based on nltk or spaCy)
Stemming and lemmatization Extract the stem or restore the base form of a word. nltk.stem.PorterStemmer()
Tokenization Split text into words or subwords. nltk.word_tokenize()
Data sampling Random sampling Randomly extract a certain proportion of samples from the data. df.sample()
Upsampling and downsampling Balance the class distribution in a dataset through oversampling (copying minority class samples) or undersampling (reducing majority class samples). SMOTE()(upsampling); RandomUnderSampler()(downsampling)
Feature Engineering Feature selection Select features that affect the target variable and remove redundant or irrelevant features. SelectKBest()
Feature extraction Create new features from raw data to improve the model's predictive power. PolynomialFeatures()
Feature scaling Scale numerical features to the same magnitude. MinMaxScaler() 、 StandardScaler()
Categorical feature mapping Feature mapping Map categorical variables to corresponding numeric codes. Custom mapping functions
Data merging and joining Merge data Combine multiple DataFrames by certain columns, supporting inner, outer, left, and right joins. pd.merge()
Concatenate data Concatenate multiple DataFrames by row or column. pd.concat()
Data reshaping Pivot tables Group data by certain dimensions and compute aggregate results. pd.pivot_table()
Data transformation Change the shape of data, such as from long to wide format or from wide to long format. df.melt() 、 df.pivot()
Data type conversion and handling String Processing Process string data, such as trimming spaces, changing case, etc. str.replace() 、 str.upper() etc.
Group computation Aggregate after grouping by a certain feature. df.groupby()
Missing value prediction and filling Use a model to predict and fill missing values Use a machine learning model (such as a regression model) to predict missing values and fill in the missing data. Custom models (such as sklearn.linear_model.LinearRegression)
Time series processing Time series missing value filling Fill missing values using time series methods (such as forward fill, backward fill). df.fillna(method='ffill')
Rolling window computation Use a sliding window for statistical computation of time series data (such as mean, standard deviation, etc.). df.rolling(window=5).mean()
Data transformation and mapping Data mapping and replacement Replace certain values in the data with other values. df.replace()

** Fill missing values: **

Example

import

pandas

as

pd

Sample data

data

=

{

'Name'

:

[

'Alice'

,

'Bob'

,

'Charlie'

,

None

]

,

       

'Age'

:

[

25

,

30

,

None

,

35

]

,

       

'City'

:

[

'New York'

,

'Los Angeles'

,

'Chicago'

,

'Houston'

]

}

df

=

pd.

DataFrame

(

data

)

Fill the missing "Age" with the mean

df

[

'Age'

]

.

fillna

(

df

[

'Age'

]

.

mean

(

)

,

inplace

=

True

)

print

(

df

)

Output:



      Name  Age           City

0    Alice   25.0       New York

1      Bob   30.0    Los Angeles

2  Charlie   30.0        Chicago

3     None   35.0        Houston

One-hot encoding:

Example

import

pandas

as

pd

Sample data

data

=

{

'City'

:

[

'New York'

,

'Los Angeles'

,

'Chicago'

,

'Houston'

]

}

df

=

pd.

DataFrame

(

data

)

Perform One-Hot encoding on the "City" column

df_encoded

=

pd.

get_dummies

(

df

,

columns

=

[

'City'

]

)

print

(

df_encoded

)

Output:



   City_Chicago  City_Houston  City_Los Angeles  City_New York

0             0             0                 0              1

1             0             0                 1              0

2             1             0                 0              0

3             0             1                 0              0

Standardization:

Example

from

sklearn.

preprocessing

import

StandardScaler

import

pandas

as

pd

Sample data

data

=

{

'Age'

:

[

25

,

30

,

35

,

40

,

45

]

,

       

'Salary'

:

[

50000

,

60000

,

70000

,

80000

,

90000

]

}

df

=

pd.

DataFrame

(

data

)

Standardize the data

scaler

=

StandardScaler

(

)

df_scaled

=

scaler.

fit_transform

(

df

)

print

(

df_scaled

)

Output:



[[-1.41421356 -1.41421356]

 [-0.70710678 -0.70710678]

 [ 0.          0.        ]

 [ 0.70710678  0.70710678]

 [ 1.41421356  1.41421356]]