Pandas doc for replace 没有例子,这里就举几个。对于那些从 R 的角度来看的人(比如我),replace 基本上是一个通用的替换函数,它结合了 R 函数 plyr::mapvalues、plyr::revalue 和 stringr::str_replace_all 的功能。由于 DSM 涵盖了单值的情况,我将介绍多值的情况。
示例系列
In [10]: x = pd.Series([1, 2, 3, 4])
In [11]: x
Out[11]:
0 1
1 2
2 3
3 4
dtype: int64
我们想用负整数替换正整数(而不是乘以 -1)。
两个值列表
一种方法是通过一个列表(或 pandas 系列)我们想要替换的值和第二个列表来替换我们想要替换的值。
In [14]: x.replace([1, 2, 3, 4], [-1, -2, -3, -4])
Out[14]:
0 -1
1 -2
2 -3
3 -4
dtype: int64
这对应于plyr::mapvalues。
值对字典
有时,拥有一个值对字典会更方便。索引是我们替换的那个,值是我们替换它的那个。
In [15]: x.replace({1: -1, 2: -2, 3: -3, 4: -4})
Out[15]:
0 -1
1 -2
2 -3
3 -4
dtype: int64
这对应于plyr::revalue。
字符串
它对字符串的工作方式类似,除了我们还可以选择使用正则表达式模式。
如果我们只是想用其他字符串替换字符串,它的工作原理和以前完全一样:
In [18]: s = pd.Series(["ape", "monkey", "seagull"])
In [22]: s
Out[22]:
0 ape
1 monkey
2 seagull
dtype: object
两个列表
In [25]: s.replace(["ape", "monkey"], ["lion", "panda"])
Out[25]:
0 lion
1 panda
2 seagull
dtype: object
字典
In [26]: s.replace({"ape": "lion", "monkey": "panda"})
Out[26]:
0 lion
1 panda
2 seagull
dtype: object
正则表达式
将所有as 替换为xs。
In [27]: s.replace("a", "x", regex=True)
Out[27]:
0 xpe
1 monkey
2 sexgull
dtype: object
将所有ls 替换为xs。
In [28]: s.replace("l", "x", regex=True)
Out[28]:
0 ape
1 monkey
2 seaguxx
dtype: object
注意seagull 中的两个ls 都被替换了。
将as 替换为xs,将ls 替换为ps
In [29]: s.replace(["a", "l"], ["x", "p"], regex=True)
Out[29]:
0 xpe
1 monkey
2 sexgupp
dtype: object
在想用相同的值替换多个不同的值的特殊情况下,可以只用一个字符串作为替换。它不能在列表中。将as 和ls 替换为ps
In [29]: s.replace(["a", "l"], "p", regex=True)
Out[29]:
0 ppe
1 monkey
2 sepgupp
dtype: object
(归功于 cmets 中的 DaveL17)