Search code examples
pythonstringpandasreplacepartial

Pandas Data Frame Partial String Replace


Given this data frame:

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

I want to replace all 99s in the entire data frame with asterisks. I've tried this:

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

...but it only worked in the case of the string 99 in column B.

Thanks in advance!


Solution

  • Use numpys character functions

    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
    

    naive time test

    enter image description here