详解pandas.replace()(替换数值)函数使用方法

  • Post category:Python

pandas.replace()函数是Pandas库中的函数,用于将DataFrame或Series中的值替换为其他值。

replace()函数在替换时可以按照要求进行精确匹配或正则匹配,也可以通过字典(dictionary)或Series对象进行替换。

作用

pandas.replace()函数可用于以下方面:

  1. 替换数据中的无效、错误或缺失值
  2. 替换现有数据集中的特定数值以满足数据分析的需要
  3. 快速替换大型数据集中的所有特定字符串

使用方法

pandas.replace()函数的基本语法如下:

dataframe/Series.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False)

参数说明:
– to_replace: 要替换的值,可以是单个值、列表或字典。
– value: 用于替换to_replace参数的值。可以是单个值、列表或字典。
– inplace:默认值为False,表示现有的Series或DataFrame对象不会被修改,而是返回一个新的Series或DataFrame对象。如果该参数设置为True,替换操作将在现有的Series或DataFrame对象上执行。
– limit:将替换操作限制为前几个匹配项。
– regex:是否启用正则表达式匹配,如需使用正则表达式替换,需将该参数设置为True。

示例1

import pandas as pd

# 创建数据集
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Cathy', 'David', 'Eric'], 
                   'age': [25, 30, 20, 45, 35], 
                   'gender': ['f', 'm', 'f', 'm', 'm']})

# 将f替换成female
df.replace('f', 'female')

输出结果为:

     name  age  gender
0   Alice   25  female
1     Bob   30       m
2   Cathy   20  female
3   David   45       m
4    Eric   35       m

上面的代码将DataFrame中gender列中的所有f替换成female。

示例2

import pandas as pd

# 创建数据集
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Cathy', 'David', 'Eric'], 
                   'age': [25, 30, 20, 45, 35], 
                   'gender': ['f', 'm', 'f', 'm', 'm']})

# 将所有的f替换成female,将所有的m替换成male
df.replace({'f': 'female', 'm': 'male'})

输出结果为:

     name  age  gender
0   Alice   25  female
1     Bob   30    male
2   Cathy   20  female
3   David   45    male
4    Eric   35    male

上面的代码用字典替换方式将DataFrame中的所有f和所有m都替换成了female和male。