pandas从列中的字符串如何删除不需要的部分
时间: 2023-12-12 15:05:46 浏览: 33
您可以使用 `str.replace()` 方法或正则表达式来删除列中的字符串中不需要的部分。
例如,假设您有一个名为 `df` 的 Pandas 数据框,并且其中有一个名为 `column_name` 的列包含以下字符串:
```
'ABC_123', 'DEF_456', 'GHI_789'
```
如果您想要删除所有字符串中的下划线和后面的数字,您可以使用以下代码:
```python
df['column_name'] = df['column_name'].str.replace(r'_\d+', '')
```
这将使用正则表达式 `r'_\d+'` 来匹配字符串中的下划线和后面的数字,然后用空字符串替换它们。
最终结果将是:
```
'ABC', 'DEF', 'GHI'
```
相关问题
pandas从列中的字符串如何删除不需要的部分如温度的后缀
可以使用pandas的`str`属性和`replace()`方法来删除不需要的部分。例如,如果你有如下的数据框:
```
import pandas as pd
df = pd.DataFrame({'temperature': ['25C', '30F', '22C', '18F']})
```
你可以使用`str.replace()`方法来删除字符串中的后缀,如下所示:
```
df['temperature'] = df['temperature'].str.replace('C', '').str.replace('F', '')
```
这将删除温度字符串中的'C'和'F'后缀。结果如下所示:
```
temperature
0 25
1 30
2 22
3 18
```
如果你想要在原始数据框上进行更改,可以使用`inplace=True`参数:
```
df['temperature'].replace({'C':'','F':''}, regex=True, inplace=True)
```
这将直接在原始数据框上进行更改,结果如下所示:
```
temperature
0 25
1 30
2 22
3 18
```
pandas 替换 部分字符串
你可以使用 `pandas` 中的 `str.replace()` 方法来替换部分字符串。以下是一个例子:
假设你有一个名为 `df` 的 `pandas` 数据帧,其中包含一个名为 `column_name` 的列,你想要将该列中的所有以 `old_string` 开头的字符串替换为 `new_string`,你可以使用以下代码:
```python
df['column_name'] = df['column_name'].str.replace('^old_string', 'new_string', regex=True)
```
这里的 `^` 符号表示只替换以 `old_string` 开头的字符串。如果你想替换包含 `old_string` 的所有字符串(而不仅仅是开头的字符串),可以省略 `^` 符号。
你也可以使用正则表达式来匹配更复杂的模式,例如:
```python
df['column_name'] = df['column_name'].str.replace('old_string1|old_string2', 'new_string', regex=True)
```
这将替换所有以 `old_string1` 或 `old_string2` 开头的字符串为 `new_string`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)