Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数据帧部分字符串替换_Python_String_Pandas_Replace_Partial - Fatal编程技术网

Python 数据帧部分字符串替换

Python 数据帧部分字符串替换,python,string,pandas,replace,partial,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 提前谢谢 问题是A列和B列中的值99类型不同:

给定此数据帧:

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'>

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


如果您想替换所有的
99
s,请尝试使用regex

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

这将完成以下工作:

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)

使用
numpy
s字符函数

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
原始时间测试

d.replace('99','*',regex=True,inplace=True)
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