Pandas df.replace() function
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
- Returns a new DataFrame (if
inplace=False), orNone(ifinplace=True)。 - returns a DataFrame in which the specified values have been replaced.
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
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Replace 'technology' with 'R&D'
df_replaced
=
df.
replace
(
'Ji shu' (a Chinese phrase)
,
'R&D'
)
(
"Data after replacement:"
)
(
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:
- The DataFrame has two rows in the 'technology' department.
- Use
df.replace('技术', '研发')Replace all 'technology' with 'R&D'. - 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
)
(
"Original data:"
)
(
df
)
(
"="
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
)
(
"Data after replacement:"
)
(
df_replaced
)
Expected output:
Original data:
姓名 城市 等级
0 张三 北京 A
1 李四 上海 B
2 王五 广州 A
3 赵六 深圳 C
==================================================
Replaced data:
姓名 城市 等级
0 张三 北京市 优秀
1 李四 上海市 良好
2 王五 广州市 优秀
3 赵六 深圳市 及格
Code analysis:
- Through the dictionary
replacementswe can specify multiple replacement rules at once. - This method is very efficient and avoids multiple calls to
replace()。
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
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Replace only 'technology' with 'R&D' in the 'department' column
df_replaced
=
df.
replace
(
{
'Department'
:
'Ji shu' (a Chinese phrase)
}
,
'R&D'
)
(
"Data after replacing only the department column:"
)
(
df_replaced
)
(
"="
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)
}
)
(
"Data after replacing with different rules for different columns:"
)
(
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:
- Use
{'部门': '技术'}You can replace values in the 'department' column only. - A nested dictionary
{'部门': {'技术': '研发'}}can specify different replacement rules for different columns.
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
)
(
"Original data:"
)
(
df
)
(
"="
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
)
(
"Data after replacing phone numbers (hiding the middle 4 digits):"
)
(
df_replaced
)
(
"="
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
)
(
"Data after unifying VIP notes:"
)
(
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:
- The first example uses a regular expression
(d{3})-(d{4})-(d{4})to match the phone number format and replace it with1****3, hiding the middle 4 digits. - The second example uses
VIPs*客户?to match both 'VIP customer' and 'VIP customer' formats, uniformly replacing them with 'VIP'.
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
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Replace NaN with 0
df_replaced
=
df.
replace
(
np.
nan
,
0
)
(
"Data after replacing NaN with 0:"
)
(
df_replaced
)
(
"="
50
)
Replace NaN with other values, such as 'unknown'
df_replaced2
=
df.
replace
(
np.
nan
,
'Unknown'
)
(
"Data after replacing NaN with 'unknown':"
)
(
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:
np.nanrepresents missing values, which can be replaced usingreplace(np.nan, value).- Choose an appropriate value to replace missing values based on the data type and business needs.
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
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Replace outliers with values in a reasonable range
df_replaced
=
df.
replace
(
{
150
:
100
,
10
:
0
}
)
(
"Data after replacing outliers:"
)
(
df_replaced
)
(
"="
50
)
Use conditional judgments to replace multiple values
df_replaced2
=
df.
replace
(
to_replace
=
[
150
,
10
]
,
value
=
[
100
,
0
]
)
(
"Replacing multiple values using a list:"
)
(
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:
- Dictionaries
{150: 100, -10: 0}Replace the outlier 150 with 100 and -10 with 0. - List
[150, -10]and[100, 0]Specify the values to replace and the replacement values separately, corresponding in order.
Notes
replace()By default the original DataFrame is not modified; to modify it in place, useinplace=Trueparameter was added.- When using regular expressions, ensure the syntax is correct; complex regular expressions may lead to unexpected results.
- Replacement operations are based on value matching and do not change the data type.
- Note that case is distinguished; 'technology' and 'Technology' are different values.
- Before performing data replacement, it is recommended to back up the original data for comparison and traceability.
Common Pandas functions