Pandas数据框部分字符串替换

时间:2017-04-13 03:22:21

标签: python string pandas replace partial

鉴于此数据框:

import pandas as pd
d=pd.DataFrame({'A':['a','b',99],'B':[1,2,'99'],'C':['abcd99',4,5]})
d

    A   B   C
0   a   1   abcd*
1   b   2   4
2   99  99  5

我想用星号替换整个数据框中的所有99个。 我试过这个:

d.replace('99','*')

...但它仅适用于B列中字符串99的情况。

提前致谢!

4 个答案:

答案 0 :(得分:3)

如果您想要替换所有99,请尝试使用正则表达式

>>> d.astype(str).replace('99','*',regex=True)

    A   B   C
0   a   1   abcd*
1   b   2   4
2   *   *   5

答案 1 :(得分:3)

这将完成这项工作:

import pandas as pd
d=pd.DataFrame({'A':['a','b',99],'B':[1,2,'99'],'C':['abcd99',4,5]})
d=d.astype(str)
d.replace('99','*',regex=True)

给出了

    A   B   C
0   a   1   abcd*
1   b   2   4
2   *   *   5

请注意,这会创建一个新的数据框。你也可以这样做:

d.replace('99','*',regex=True,inplace=True)

答案 2 :(得分:2)

问题是A列中的值99和B列的类型不同:

>>> type(d.loc[2,"A"])
<class 'int'>
>>> type(d.loc[2,"B"])
<class 'str'>

您可以通过df.astype()将数据框转换为字符串类型然后替换,从而产生:

>>> d.astype(str).replace("99","*")
   A  B       C
0  a  1  abcd99
1  b  2       4
2  *  *       5

编辑:使用正则表达式是其他答案给出的正确解决方案。我出于某种原因错过了你的DataFrame中的abcd *。

请将此保留在此处,以防万一对其他人有帮助。

答案 3 :(得分:2)

使用numpy个字符函数

d.values[:] = np.core.defchararray.replace(d.values.astype(str), '99', '*')
d

   A  B      C
0  a  1  abcd*
1  b  2      4
2  *  *      5

天真时间测试

enter image description here

相关问题