Python pandas的replace函数的等价方法是什么?

23
在R中,有一个非常有用的replace函数。本质上,它可以在数据框(data frame)的给定列中进行条件重新赋值。可以这样使用:replace(df$column, df$column==1,'Type 1'); 在pandas中如何实现同样的功能呢?可以使用lambda和apply吗?如果是这样,如何获取给定列的引用,而不是整个行?或者应该在data_frame.values上使用np.where?似乎我错过了一个非常明显的东西。欢迎任何建议。
2个回答

31

pandas 也有一个 replace 方法:

In [25]: df = DataFrame({1: [2,3,4], 2: [3,4,5]})

In [26]: df
Out[26]: 
   1  2
0  2  3
1  3  4
2  4  5

In [27]: df[2]
Out[27]: 
0    3
1    4
2    5
Name: 2

In [28]: df[2].replace(4, 17)
Out[28]: 
0     3
1    17
2     5
Name: 2

In [29]: df[2].replace(4, 17, inplace=True)
Out[29]: 
0     3
1    17
2     5
Name: 2

In [30]: df
Out[30]: 
   1   2
0  2   3
1  3  17
2  4   5

或者你可以使用类似 numpy 的高级索引:

In [47]: df[1]
Out[47]: 
0    2
1    3
2    4
Name: 1

In [48]: df[1] == 4
Out[48]: 
0    False
1    False
2     True
Name: 1

In [49]: df[1][df[1] == 4]
Out[49]: 
2    4
Name: 1

In [50]: df[1][df[1] == 4] = 19

In [51]: df
Out[51]: 
    1   2
0   2   3
1   3  17
2  19   5

我很痛心,我没有足够认真地阅读手册。 - ivan-k
说实话,除非有什么真正困扰我,否则我几乎从不阅读手册。但使用像IPython这样的智能解释器的一个优点是,您可以构建一个名为“df”的对象,然后使用制表符完成来查看其中包含的方法。 - DSM
这确实是真的。iPython 真是美妙的事物。为了辩护,替换函数在这里没有列出。 - ivan-k
嘿!也许我的从不阅读手册的策略比我想象的更有道理!:^) - DSM
这是这里,哈哈 =P - Chang She

9

Pandas文档中的replace没有任何示例,因此我将在此提供一些示例。对于那些像我一样从R角度来看待这个问题的人来说,replace基本上是一个多功能替换函数,它结合了R函数plyr::mapvaluesplyr::revaluestringr::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

正则表达式

x 替换所有的 a

In [27]: s.replace("a", "x", regex=True)
Out[27]: 
0        xpe
1     monkey
2    sexgull
dtype: object

将所有的 l 替换为 x

In [28]: s.replace("l", "x", regex=True)
Out[28]: 
0        ape
1     monkey
2    seaguxx
dtype: object

请注意,seagull中的两个l都被替换了。
a替换为x,将l替换为p
In [29]: s.replace(["a", "l"], ["x", "p"], regex=True)
Out[29]: 
0        xpe
1     monkey
2    sexgupp
dtype: object

在一种特殊情况下,如果想要用相同的值替换多个不同的值,可以只使用一个字符串作为替换值。它不能在列表中。将al替换为p
In [29]: s.replace(["a", "l"], "p", regex=True)
Out[29]: 
0        ppe
1     monkey
2    sepgupp
dtype: object

(感谢评论区的DaveL17)

2
对于一系列很好的示例,点赞。对于未来的访问者,您还可以使用单个值替换多个值s.replace(["a", "l"], "x", regex=True),但是单个替换值不能在列表中('from'和'to'列表必须具有相等的值才能正常工作)。 - DaveL17
我添加了你的示例。 - CoderGuy123
谢谢。我不能再编辑我上面的评论了,但更好的描述应该是(为了起作用,“from”和“to”列表必须具有相同的长度。) - DaveL17

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接