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

Pandas df.replace() function

Pandas df.replace() function

Pandas Common Functions Common Pandas functions


df.replace() is a function in Pandas used to replace data in a DataFrame.

Data replacement is a common operation in data cleaning,replace() helping you replace specific values with new values, supporting flexible methods such as single-value replacement, multi-value replacement, and regular-expression replacement. This is very useful in scenarios such as handling outliers, unifying data formats, and encoding conversion.


Basic syntax and parameters

replace() is a member function of DataFrame, called via the dot operator . to call it.

Syntax format



DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')

Parameter Description

Parameters Type Required Description Default value
to_replace str, regex, list, dict, int, float, None Required The value to replace. It can be a single value, a list of values, a dictionary, a regular expression, etc. None
value scalar, dict, list, str, regex, None Optional The replacement value. If to_replace it is a dictionary, this item can be omitted; otherwise, this item is required. None
inplace bool Optional If it is True, modify the original DataFrame directly without returning a new object; if False, a new DataFrame is returned and the original data is unchanged. False
limit int Optional Specify the maximum number of replacements. None
regex bool or str Optional If it is True, and replace to_replace treat as a regular expression. False
method str Optional When to_replace used when it is a list.'pad' or 'ffill' means forward fill;'backfill' or 'bfill' means backward fill. 'pad'

Return value description


Example

Let us thoroughly master replace() through a series of examples from simple to complex.

Example 1: Single-value replacement

Replace a specific value in a DataFrame with a new value.

Example

import

pandas

as

pd

import

numpy

as

np

Create a DataFrame with duplicate data

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

]

,

   

'Department'

:

[

'Ji shu' (a Chinese phrase)

,

'Marketing'

,

'Ji shu' (a Chinese phrase)

,

'Marketing'

]

,

   

'Salary'

:

[

5000

,

6000

,

5500

,

7000

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Replace 'technology' with 'R&D'

df_replaced

=

df.

replace

(

'Ji shu' (a Chinese phrase)

,

'R&D'

)

print

(

"Data after replacement:"

)

print

(

df_replaced

)

Expected output:



Original data:

    姓名  部门   薪资

0  张三  技术  5000

1  李四  市场  6000

2  王五  技术  5500

3  赵六  市场  7000

==================================================

Replaced data:

    姓名   部门  薪资

0  张三  研发  5000

1  李四  市场  6000

2  王五  研发  5500

3  赵六  市场  7000

Code analysis:

  1. The DataFrame has two rows in the 'technology' department.
  2. Use df.replace('技术', '研发') Replace all 'technology' with 'R&D'.
  3. This method replaces all matching values in the DataFrame.

Example 2: One-to-one replacement of multiple values

Use a dictionary to replace multiple different values at once.

Example

import

pandas

as

pd

Create a DataFrame with data that needs to be replaced

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

]

,

   

'City'

:

[

'Beijing'

,

'Shanghai'

,

'Guangzhou'

,

'Shenzhen'

]

,

   

'grade'

:

[

'A'

,

'B'

,

'A'

,

'C'

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Perform multiple replacements using a dictionary

replacements

=

{

   

'Beijing'

:

'Beijing'

,

   

'Shanghai'

:

'Shanghai'

,

   

'Guangzhou'

:

'Guangzhou'

,

   

'Shenzhen'

:

'Shenzhen'

,

   

'A'

:

'Excellent'

,

   

'B'

:

'Good'

,

   

'C'

:

'Pass'

}

df_replaced

=

df.

replace

(

replacements

)

print

(

"Data after replacement:"

)

print

(

df_replaced

)

Expected output:



Original data:

    姓名  城市  等级

0  张三  北京   A

1  李四  上海   B

2  王五  广州   A

3  赵六  深圳   C

==================================================

Replaced data:

    姓名   城市  等级

0  张三  北京市  优秀

1  李四  上海市  良好

2  王五  广州市  优秀

3  赵六  深圳市  及格

Code analysis:

Example 3: Replacing values in a specific column

You can replace values in a specific column only, without affecting other columns.

Example

import

pandas

as

pd

Create a DataFrame

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

]

,

   

'Department'

:

[

'Ji shu' (a Chinese phrase)

,

'Marketing'

,

'Ji shu' (a Chinese phrase)

,

'Marketing'

]

,

   

'position'

:

[

'Ji shu' (a Chinese phrase)

,

'Marketing'

,

'Ji shu' (a Chinese phrase)

,

'Marketing'

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Replace only 'technology' with 'R&D' in the 'department' column

df_replaced

=

df.

replace

(

{

'Department'

:

'Ji shu' (a Chinese phrase)

}

,

'R&D'

)

print

(

"Data after replacing only the department column:"

)

print

(

df_replaced

)

print

(

"="

50

)

You can also use a nested dictionary to apply different replacement rules to different columns

df_replaced2

=

df.

replace

(

{

'Department'

:

{

'Ji shu' (a Chinese phrase)

:

'R&D'

,

'Marketing'

:

'sales'

}

,

'position'

:

'Ji shu' (a Chinese phrase)

}

)

print

(

"Data after replacing with different rules for different columns:"

)

print

(

df_replaced2

)

Expected output:



Original data:

    姓名  部门  职位

0  张三  技术  技术

1  李四  市场  市场

2  王五  技术  技术

3  赵六  市场  市场

==================================================

Only replace data after the department column:

    姓名   部门  职位

0  张三  研发  技术

1  李四  市场  市场

2  王五  研发  技术

3  赵六  市场  市场

==================================================

Data after replacement using different rules for different columns:

    姓名   部门  职位

0  张三  研发  研发

1  李四  销售  市场

2  王五  研发  研发

3  赵六  销售  市场

Code analysis:

Example 4: Replacing with regular expressions

regex=True The parameter allows replacement using regular expressions, which is very useful when working with pattern-matched text.

Example

import

pandas

as

pd

Create a DataFrame containing text that needs to be processed with regular expressions

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

]

,

   

'phone'

:

[

'138-0000-0000'

,

'139-1111-1111'

,

'137-2222-2222'

,

'136-3333-3333'

]

,

   

'note'

:

[

'normal'

,

'VIP customer'

,

'normal'

,

'VIP customer'

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Use a regular expression to replace separators in phone numbers

df_replaced

=

df.

replace

(

to_replace

=

r

'(d{3})-(d{4})-(d{4})'

,

value

=

r

'1****3'

,

regex

=

True

)

print

(

"Data after replacing phone numbers (hiding the middle 4 digits):"

)

print

(

df_replaced

)

print

(

"="

50

)

Replace 'VIP customer' in the note (there may be spacing differences)

df_replaced2

=

df.

replace

(

to_replace

=

r

'VIPs*customer?'

,

value

=

'VIP'

,

regex

=

True

)

print

(

"Data after unifying VIP notes:"

)

print

(

df_replaced2

)

Expected output:



Original data:

    姓名          电话        备注

0  张三  138-0000-0000       正常

1  李四  139-1111-1111   VIP客户

2  王五  137-2222-2222       正常

3  赵六  136-3333-3333  VIP 客户

==================================================

Data after replacing the phone number (hiding the middle 4 digits):

    姓名          电话  备注

0  张三  138****0000   正常

1  李四  139****1111  VIP客户

2  王五  137****2222   正常

3  赵六  136****3333  VIP 客户

==================================================

Unified VIP Notes Data:

    姓名          电话  备注

0  张三  138-0000-0000  正常

1  李四  139-1111-1111  VIP

2  王五  137-2222-2222  正常

3  赵六  136-3333-3333  VIP

Code analysis:

Example 5: Replacing missing values NaN

replace() can also be used to replace missing values NaN, which is a common operation in data cleaning.

Example

import

pandas

as

pd

import

numpy

as

np

Create a DataFrame with missing values

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

]

,

   

'Age'

:

[

25

,

np.

nan

,

35

,

np.

nan

]

,

   

'Salary'

:

[

5000

,

6000

,

np.

nan

,

8000

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Replace NaN with 0

df_replaced

=

df.

replace

(

np.

nan

,

0

)

print

(

"Data after replacing NaN with 0:"

)

print

(

df_replaced

)

print

(

"="

50

)

Replace NaN with other values, such as 'unknown'

df_replaced2

=

df.

replace

(

np.

nan

,

'Unknown'

)

print

(

"Data after replacing NaN with 'unknown':"

)

print

(

df_replaced2

)

Expected output:



Original data:

    姓名   年龄    薪资

0  张三  25.0  5000.0

1  李四   NaN  6000.0

2  王五  35.0     NaN

3  赵六   NaN  8000.0

==================================================

# Data after replacing NaN with 0:

    姓名   年龄  薪资

0  张三  25.0  5000

1  李四   0.0  6000

2  王五  35.0     0

3  赵六   0.0  8000

==================================================

Data after replacing NaN with 'Unknown':

    姓名   年龄    薪资

0  张三  25.0  5000.0

1  李四  未知  6000.0

2  王五  35.0    未知

3  赵六  未知  8000.0

Code analysis:

Example 6: Numeric replacement

can replace numeric data for data standardization or outlier handling.

Example

import

pandas

as

pd

Create a DataFrame containing outliers

data

=

{

   

'Student'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

,

'Qian Qi'

]

,

   

'Score'

:

[

85

,

150

,

78

,

92

,

10

]

 

150 and -10 are outliers

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Replace outliers with values in a reasonable range

df_replaced

=

df.

replace

(

{

150

:

100

,

10

:

0

}

)

print

(

"Data after replacing outliers:"

)

print

(

df_replaced

)

print

(

"="

50

)

Use conditional judgments to replace multiple values

df_replaced2

=

df.

replace

(

to_replace

=

[

150

,

10

]

,

value

=

[

100

,

0

]

)

print

(

"Replacing multiple values using a list:"

)

print

(

df_replaced2

)

Expected output:



Original data:

    学生  成绩

0  张三    85

1  李四   150

2  王五    78

3  赵六    92

4  钱七   -10

==================================================

Data after replacing outliers:

    学生  成绩

0  张三    85

1  李四   100

2  王五    78

3  赵六    92

4  钱七     0

==================================================

Use a list to replace multiple values:

    学生  成绩

0  张三    85

1  李四   100

2  王五    78

3  赵六    92

4  钱七     0

Code analysis:


Notes


Pandas Common Functions Common Pandas functions