pandas筛选字符串的后5位字符串
时间: 2023-10-10 07:05:29 浏览: 48
假设有一个DataFrame df,其中有一列为字符串类型的数据,可以使用str.slice(-5)方法来筛选字符串的后5位字符串,示例如下:
```python
import pandas as pd
df = pd.DataFrame({'string_col': ['abcdefg', 'xyz12345', '123456']})
df['last_5_chars'] = df['string_col'].str.slice(-5)
print(df)
```
输出结果为:
```
string_col last_5_chars
0 abcdefg cdefg
1 xyz12345 12345
2 123456 23456
```
可以看到,新添加的一列last_5_chars即为原字符串列的后5位字符串。
相关问题
pandas筛选包含“*”的字符串
要筛选包含星号(*)的字符串,您可以使用`str.contains()`方法结合适当的正则表达式来实现。下面是一个示例代码:
```python
import pandas as pd
# 创建一个包含字符串的示例Series
data = pd.Series(['apple', 'banana*', 'cherry', 'grape*'])
# 使用正则表达式匹配包含星号的字符串
filtered_data = data[data.str.contains('\*')]
# 打印筛选结果
print(filtered_data)
```
运行上述代码后,您将得到如下输出:
```
1 banana*
3 grape*
dtype: object
```
在这个示例中,`data`是一个`pandas`的`Series`对象,其中包含了一些字符串。我们使用`str.contains()`方法并传入正则表达式`\*`来匹配包含星号的字符串。然后,将这个条件应用于`data`,以获取筛选后的结果。
请注意,正则表达式中的星号需要进行转义,因为星号在正则表达式中具有特殊含义。所以我们使用`\*`来匹配实际的星号字符。
您可以根据实际情况调整代码中的`data`和正则表达式来适应自己的需求。
pandas查找excel重复字符串
可以使用pandas的duplicated()方法来查找Excel中的重复字符串。具体步骤如下:
1. 使用pandas的read_excel()方法读取Excel文件,将数据读取到一个DataFrame中。
2. 使用duplicated()方法查找重复的字符串,该方法返回一个布尔型的Series,其中True表示该行数据是重复的,False表示不重复。
3. 将重复的数据筛选出来,可以使用loc[]方法或者boolean indexing来实现。
以下是示例代码:
```python
import pandas as pd
# 读取Excel文件
df = pd.read_excel('data.xlsx')
# 查找重复的字符串
duplicated = df.duplicated('column_name')
# 筛选出重复的数据
duplicate_data = df.loc[duplicated, :]
```
其中,'column_name'是要查找重复字符串的列名。如果要查找多列重复数据,可以传入一个列表,例如duplicated = df.duplicated(['column_name_1', 'column_name_2'])。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)