一、简介
dataframe.replace()
函数用于替换dataframe中的指定值。该函数允许使用单个值、列表、字典或正则表达式进行替换操作,非常灵活。
二、语法和参数
dataframe.replace(to_replace=none, value=none, inplace=false, limit=none, regex=false, method='pad')
- to_replace:需要替换的值,可以是单个值、列表、字典或正则表达式。
- value:替换后的值,可以是单个值、列表或字典。
- inplace:布尔值,是否在原dataframe上进行替换,默认false。
- limit:整数,限制替换的数量。
- regex:布尔值,是否将
to_replace
作为正则表达式处理,默认false。 - method:当
to_replace
是na值时,指定填充方法,如’pad’、‘ffill’、‘bfill’。
三、实例
3.1 替换单个值
import pandas as pd data = {'a': [1, 2, 3], 'b': [4, 5, 6]} df = pd.dataframe(data) # 替换值 df.replace(1, 10, inplace=true) print(df)
输出:
a b
0 10 4
1 2 5
2 3 6
3.2 使用字典替换值
import pandas as pd data = {'a': [1, 2, 3], 'b': [4, 5, 6]} df = pd.dataframe(data) # 使用字典替换值 df.replace({'a': 1, 'b': 4}, 100, inplace=true) print(df)
输出:
a b
0 100 100
1 2 5
2 3 6
3.3 使用列表替换值
import pandas as pd data = {'a': [1, 2, 3], 'b': [4, 5, 6]} df = pd.dataframe(data) # 使用列表替换值 df.replace([1, 4], [100, 400], inplace=true) print(df)
输出:
a b
0 100 400
1 2 5
2 3 6
3.4 使用正则表达式替换值
import pandas as pd data = {'a': ['foo', 'bar', 'baz'], 'b': ['fuz', 'buz', 'faz']} df = pd.dataframe(data) # 使用正则表达式替换值 df.replace(to_replace=r'^b', value='new', regex=true, inplace=true) print(df)
输出:
a b
0 foo fuz
1 new newz
2 new faz
四、注意事项
- 当使用
inplace=true
时,dataframe会直接修改,无需重新赋值。 - 当
to_replace
为字典时,value
的值必须与to_replace
的键相对应。 - 使用正则表达式时,需将
regex
参数设置为true。
到此这篇关于pandas中dataframe.replace()函数的实现的文章就介绍到这了,更多相关pandas dataframe.replace()内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论