Python Pandas 筛选数据以及字符串替换

 

 str.replace使用示例

假设有一个DataFrame `df`,其中有一个列名为`text`,包含一些文本字符串:

```
import pandas as pd

data = {'text': ['hello world', 'foo bar', 'hello there']}
df = pd.DataFrame(data)
```

我们可以使用`str.replace`方法来替换字符串。比如我们想把字符串中的“hello”替换为“hi”,代码如下:

```
df['text'] = df['text'].str.replace('hello', 'hi')
```

这将会把`df['text']`中的“hello”全部替换为“hi”。最后输出结果如下:

```
         text
0  hi world
1  foo bar
2  hi there
```

`str.replace`方法接受两个参数:要替换的字符串和用来替换的字符串。这两个参数都可以是正则表达式,从而可以实现更加灵活的替换操作。

猜你喜欢

转载自blog.csdn.net/Ghjkku/article/details/131387062