Pandas 数据框部分字符串替换

Pandas Data Frame Partial String Replace

鉴于此数据框:

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。

提前致谢!

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

>>> 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*。

将把它留在这里,以防对其他人有帮助。

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

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

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

这将完成工作:

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)

使用 numpys 字符函数

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

天真的时间测试