Pandas数据帧部分字符串表示

2024-10-01 04:46:44 发布

您现在位置:Python中文网/ 问答频道 /正文

给定此数据帧:

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。 我试过了:

^{pr2}$

…但它只适用于B列中的字符串99

提前谢谢!在


Tags: 数据字符串importdataframepandasas星号pd
3条回答

如果要替换所有99,请尝试使用regex

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

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

使用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

天真时间测试

{a1}

这将完成以下工作:

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)

这给了

^{pr2}$

注意,这将创建一个新的数据帧。也可以就地执行:

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

相关问题 更多 >