mars.dataframe.DataFrame.replace#

DataFrame.replace(to_replace=NoDefault.no_default, value=NoDefault.no_default, inplace=False, limit=None, regex=False, method=NoDefault.no_default)#

to_replace中给定的值替换为value

数据框的值会动态地被其他值替换。这与使用 .loc.iloc 更新有所不同,它们需要您指定一个位置来使用某个值进行更新。

Parameters
  • to_replace (str, regex, list, dict, Series, int, float, 或 None) –

    如何找到将被替换的值。

    • 数字、字符串或正则表达式:

      • 数字: 与 to_replace 相等的数字值将被替换为 value

      • 字符串: 完全匹配 to_replace 的字符串将被替换为 value

      • 正则表达式: 匹配 to_replace 的正则表达式将被替换为 value

    • 字符串、正则表达式或数字的列表:

      • 首先,如果 to_replacevalue 都是列表,它们 必须 长度相同。

      • 其次,如果 regex=True两个 列表中的所有字符串都将被解释为正则表达式,否则它们将直接匹配。这对 value 并没有太大影响,因为您只能使用少量可能的替代正则表达式。

      • 字符串、正则表达式和数字的规则如上所述。

    • 字典:

      • 字典可用于为不同的现有值指定不同的替换值。例如, {'a': 'b', 'y': 'z'} 将值‘a’替换为‘b’,将‘y’替换为‘z’。以这种方式使用字典时,value 参数应为 None

      • 对于 DataFrame,字典可以指定在不同列中替换不同的值。例如, {'a': 1, 'b': 'z'} 在列‘a’中查找值1,在列‘b’中查找值‘z’,并将这些值替换为在 value 中指定的内容。在这种情况下,value 参数不应为 None。您可以将这种情况视为传递两个列表的特例,只是您正在指定要搜索的列。

      • 对于 DataFrame 嵌套字典,例如, {'a': {'b': np.nan}},读取方式如下: 在列‘a’中查找值‘b’,并将其替换为 NaN。使用嵌套字典时,value 参数应为 None。您也可以嵌套正则表达式。请注意,列名(嵌套字典中的顶层字典键) 不能 是正则表达式。

    • None:

      • 这意味着 regex 参数必须是字符串、编译的正则表达式或包含此类元素的列表、字典、ndarray 或 Series。如果 value 也是 None,那么这 必须 是嵌套字典或 Series。

    请参见示例部分以获取每个这些的示例。

  • value (标量, 字典, 列表, 字符串, 正则表达式, 默认为 None) – 用于替换任何匹配 to_replace 的值的值。 对于 DataFrame,可以使用值的字典来指定每一列使用哪个值(不在字典中的列将不会被填充)。也允许使用正则表达式、字符串以及这类对象的列表或字典。

  • inplace (bool, 默认值为 False) – 如果为 True,表示在原地操作。注意:这会修改对该对象的任何其他视图(例如,来自 DataFrame 的一列)。如果为 True,返回调用者。

  • limit (int, 默认值为 None) – 向前或向后填充的最大间隙大小。

  • regex (布尔值或与to_replace相同类型,默认值为False) – 是否将to_replace和/或value解释为正则表达式。如果这是True,那么to_replace 必须是一个字符串。或者,这可以是一个正则表达式,或一组正则表达式的列表、字典或数组,在这种情况下to_replace必须是None

  • method ({‘pad’, ‘ffill’, ‘bfill’, None}) – 当 to_replace 是一个标量、列表或元组并且 valueNone 时用于替换的方法。

Returns

替换后的对象。

Return type

数据框

Raises
  • AssertionError

    • 如果 regex 不是 bool,并且 to_replace 不是 None

  • 类型错误

    • 如果 to_replace 是一个 dictvalue 不是一个 list, dict, ndarray, 或 Series * 如果 to_replaceNoneregex 不能编译 成正则表达式或是一个列表、字典、ndarray 或 Series。 * 当替换多个 booldatetime64 对象时, 如果 to_replace 的参数与被替换值的类型不匹配

  • ValueError

    • 如果传递给 to_replacevaluelistndarray 的长度不相同。

另请参阅

DataFrame.fillna

填充缺失值。

DataFrame.where

根据布尔条件替换值。

Series.str.replace

简单的字符串替换。

备注

  • 正则替换是在后台通过 re.sub 执行的。对于 re.sub 的替换规则是一样的。

  • 正则表达式仅在字符串上进行替换,这意味着你不能提供,比如说,一个匹配浮点数的正则表达式,并期望你的数据框中具有数字数据类型的列被匹配。然而,如果这些浮点数字符串,那么你可以这样做。

  • 这个方法有很多选项。鼓励你尝试和使用这个方法,以便对它的工作原理有更深入的理解。

  • 当字典用作to_replace值时,就像字典中的键是to_replace部分,字典中的值是值参数。

示例

标量 `to_replace` 和 `value`

>>> import mars.tensor as mt
>>> import mars.dataframe as md
>>> s = md.Series([0, 1, 2, 3, 4])
>>> s.replace(0, 5).execute()
0    5
1    1
2    2
3    3
4    4
dtype: int64
>>> df = md.DataFrame({'A': [0, 1, 2, 3, 4],
...                    'B': [5, 6, 7, 8, 9],
...                    'C': ['a', 'b', 'c', 'd', 'e']})
>>> df.replace(0, 5).execute()
   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).execute()
   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]).execute()
   A  B  C
0  4  5  a
1  3  6  b
2  2  7  c
3  1  8  d
4  4  9  e
>>> s.replace([1, 2], method='bfill').execute()
0    0
1    3
2    3
3    3
4    4
dtype: int64

类似字典的 `to_replace`

>>> df.replace({0: 10, 1: 100}).execute()
     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).execute()
     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}}).execute()
     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 = md.DataFrame({'A': ['bat', 'foo', 'bait'],
...                    'B': ['abc', 'bar', 'xyz']})
>>> df.replace(to_replace=r'^ba.$', value='new', regex=True).execute()
      A    B
0   new  abc
1   foo  new
2  bait  xyz
>>> df.replace({'A': r'^ba.$'}, {'A': 'new'}, regex=True).execute()
      A    B
0   new  abc
1   foo  bar
2  bait  xyz
>>> df.replace(regex=r'^ba.$', value='new').execute()
      A    B
0   new  abc
1   foo  new
2  bait  xyz
>>> df.replace(regex={r'^ba.$': 'new', 'foo': 'xyz'}).execute()
      A    B
0   new  abc
1   xyz  new
2  bait  xyz
>>> df.replace(regex=[r'^ba.$', 'foo'], value='new').execute()
      A    B
0   new  abc
1   new  new
2  bait  xyz

注意,当替换多个 booldatetime64 对象时,to_replace 参数中的数据类型必须与被替换值的数据类型匹配:

>>> df = md.DataFrame({'A': [True, False, True],
...                    'B': [False, True, False]})
>>> df.replace({'a string': 'new value', True: False})  # raises.execute()
Traceback (most recent call last):
    ....execute()
TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'

这会引发一个 TypeError,因为其中一个 dict 键的类型不正确,无法进行替换。

比较 s.replace({'a': None})s.replace('a', None) 的行为,以了解 to_replace 参数的特殊性:

>>> s = md.Series([10, 'a', 'a', 'b', 'a'])

当一个字典被用作to_replace值时,就像字典中的值等于value参数。s.replace({'a': None}) 相当于 s.replace(to_replace={'a': None}, value=None, method=None):

>>> s.replace({'a': None}).execute()
0      10
1    None
2    None
3       b
4    None
dtype: object

value=None 并且 to_replace 是标量、列表或元组时, replace 使用方法参数(默认为‘pad’)来进行替换。这就是为什么在这个情况下,第1行和第2行的‘a’值被替换为10,第4行的‘b’被替换的原因。命令 s.replace('a', None) 实际上等效于 s.replace(to_replace='a', value=None, method='pad'):

>>> s.replace('a', None).execute()
0    10
1    10
2    10
3     b
4     b
dtype: object