pandas.DataFrame.replace#
- DataFrame.replace(to_replace=None, value=<no_default>, *, inplace=False, regex=False)[源代码]#
用value替换to_replace中给定的值。
Series/DataFrame 的值会被动态替换为其他值。这与使用
.loc或.iloc进行更新不同,后者需要你指定一个位置来用某个值进行更新。- 参数:
- to_replacestr, regex, list, dict, Series, int, float, 或 None
如何查找将被替换的值。
numeric, str 或 regex
numeric: 等于 to_replace 的数值将被替换为 value
str: 精确匹配 to_replace 的字符串将被替换为 value
regex: 匹配 to_replace 的正则表达式将被替换为 value
str, regex 或 numeric 的列表
首先,如果 to_replace 和 value 都是列表,它们必须具有相同的长度。
其次,如果
regex=True,那么两个列表中的所有字符串都将被解释为正则表达式,否则它们将直接匹配。这对于 value 来说差别不大,因为只有少数几种可能的替换正则表达式可以使用。str, regex 和 numeric 的规则如上所述。
dict
可以使用字典来指定对不同现有值使用不同的替换值。例如,
{'a': 'b', 'y': 'z'}会将值 'a' 替换为 'b',将 'y' 替换为 'z'。要这样使用字典,则不应提供可选的 value 参数。对于 DataFrame,字典可以指定在不同列中替换不同的值。例如,
{'a': 1, 'b': 'z'}会在列 'a' 中查找值 1,在列 'b' 中查找值 'z',并将这些值替换为 value 中指定的值。在这种情况下,value 参数不应为None。您可以将其视为传递两个列表的特殊情况,只不过您指定了要搜索的列。对于 DataFrame,嵌套字典,例如
{'a': {'b': np.nan}},其读取方式如下:在列 'a' 中查找值 'b',并将其替换为 NaN。要以这种方式使用嵌套字典,不应指定可选的 value 参数。您也可以嵌套正则表达式。请注意,列名(嵌套字典中的顶层字典键)不能是正则表达式。
None
这意味着 regex 参数必须是字符串、已编译的正则表达式,或此类元素的列表、字典、ndarray 或 Series。如果 value 也为
None,则必须是嵌套字典或 Series。
请参阅示例部分,了解每种情况的示例。
- valuescalar, dict, list, str, regex, default None
用于替换匹配 to_replace 的任何值的值。对于 DataFrame,可以使用字典值来指定每个列使用哪个值(不在字典中的列不会被填充)。还允许使用正则表达式、字符串以及此类对象的列表或字典。
- inplacebool, default False
如果为 True,则执行原地操作。
- regexbool 或与 to_replace 相同的类型,default False
是否将 to_replace 和/或 value 解释为正则表达式。或者,它可以是正则表达式,或者是一个正则表达式列表、字典或数组,在这种情况下 to_replace 必须为
None。
- 返回:
- Series/DataFrame
替换后的对象。
- 引发:
- AssertionError
如果 regex 不是
bool且 to_replace 不是None。
- TypeError
如果 to_replace 不是标量、类数组、
dict或None如果 to_replace 是
dict且 value 不是list、dict、ndarray或Series如果 to_replace 为
None且 regex 无法编译成正则表达式或是一个列表、字典、ndarray 或 Series。当替换多个
bool或datetime64对象且 to_replace 的参数与被替换值的类型不匹配时
- ValueError
如果将
list或ndarray传递给 to_replace 和 value 但它们长度不一致时。
另请参阅
Series.fillna填充 NA 值。
DataFrame.fillna填充 NA 值。
Series.where根据布尔条件替换值。
DataFrame.where根据布尔条件替换值。
DataFrame.map逐元素地将函数应用于 DataFrame。
Series.map根据输入映射或函数映射 Series 的值。
Series.str.replace简单字符串替换。
注意
正则表达式替换在底层使用
re.sub进行。re.sub的替换规则相同。正则表达式只能在字符串上进行替换,这意味着您不能提供一个匹配浮点数的正则表达式,并期望 DataFrame 中具有数值 dtype 的列能够匹配。但是,如果这些浮点数是字符串,那么您可以这样做。
此方法有很多选项。建议您进行实验和探索此方法,以直观地了解其工作原理。
当字典用作 to_replace 值时,就像字典中的键是 to_replace 部分,字典中的值是 value 参数。
示例
标量 `to_replace` 和 `value`
>>> s = pd.Series([1, 2, 3, 4, 5]) >>> s.replace(1, 5) 0 5 1 2 2 3 3 4 4 5 dtype: int64
>>> df = pd.DataFrame( ... { ... "A": [0, 1, 2, 3, 4], ... "B": [5, 6, 7, 8, 9], ... "C": ["a", "b", "c", "d", "e"], ... } ... ) >>> df.replace(0, 5) A B C 0 5 5 a 1 1 6 b 2 2 7 c 3 3 8 d 4 4 9 e
类列表 `to_replace`
>>> df.replace([0, 1, 2, 3], 4) A B C 0 4 5 a 1 4 6 b 2 4 7 c 3 4 8 d 4 4 9 e
>>> df.replace([0, 1, 2, 3], [4, 3, 2, 1]) A B C 0 4 5 a 1 3 6 b 2 2 7 c 3 1 8 d 4 4 9 e
类字典 `to_replace`
>>> df.replace({0: 10, 1: 100}) A B C 0 10 5 a 1 100 6 b 2 2 7 c 3 3 8 d 4 4 9 e
>>> df.replace({"A": 0, "B": 5}, 100) A B C 0 100 100 a 1 1 6 b 2 2 7 c 3 3 8 d 4 4 9 e
>>> df.replace({"A": {0: 100, 4: 400}}) A B C 0 100 5 a 1 1 6 b 2 2 7 c 3 3 8 d 4 400 9 e
正则表达式 `to_replace`
>>> df = pd.DataFrame({"A": ["bat", "foo", "bait"], "B": ["abc", "bar", "xyz"]}) >>> df.replace(to_replace=r"^ba.$", value="new", regex=True) A B 0 new abc 1 foo new 2 bait xyz
>>> df.replace({"A": r"^ba.$"}, {"A": "new"}, regex=True) A B 0 new abc 1 foo bar 2 bait xyz
>>> df.replace(regex=r"^ba.$", value="new") A B 0 new abc 1 foo new 2 bait xyz
>>> df.replace(regex={r"^ba.$": "new", "foo": "xyz"}) A B 0 new abc 1 xyz new 2 bait xyz
>>> df.replace(regex=[r"^ba.$", "foo"], value="new") A B 0 new abc 1 new new 2 bait xyz
比较
s.replace({'a': None})和s.replace('a', None)的行为,以了解 to_replace 参数的特殊性>>> s = pd.Series([10, "a", "a", "b", "a"])
当使用字典作为 to_replace 值时,就好像字典中的值等于 value 参数。
s.replace({'a': None})等同于s.replace(to_replace={'a': None}, value=None)>>> s.replace({"a": None}) 0 10 1 None 2 None 3 b 4 None dtype: object
如果为
value显式传递了None,则会生效>>> s.replace("a", None) 0 10 1 None 2 None 3 b 4 None dtype: object
当
regex=True,value不为None且 to_replace 是字符串时,替换将应用于 DataFrame 的所有列。>>> df = pd.DataFrame( ... { ... "A": [0, 1, 2, 3, 4], ... "B": ["a", "b", "c", "d", "e"], ... "C": ["f", "g", "h", "i", "j"], ... } ... )
>>> df.replace(to_replace="^[a-g]", value="e", regex=True) A B C 0 0 e e 1 1 e e 2 2 e h 3 3 e i 4 4 e j
如果
value不为None且 to_replace 是字典,则字典键将是应用替换的 DataFrame 列。>>> df.replace(to_replace={"B": "^[a-c]", "C": "^[h-j]"}, value="e", regex=True) A B C 0 0 e f 1 1 e g 2 2 e e 3 3 d e 4 4 e e