Pandas Series.str.find() 方法



Pandas 中的 Series.str.find() 方法用于返回 Series 中每个字符串中找到指定子字符串的最低索引。如果未找到子字符串,则返回 -1。

此方法等效于标准 Python str.find() 方法。它可用于在 Pandas Series 或 DataFrame 的列中的字符串内查找子字符串,并通过可选的开始和结束参数提供灵活性。

语法

以下是 Pandas Series.str.find() 方法的语法:

Series.str.find(sub, start=0, end=None)

参数

Series.str.find() 方法接受以下参数:

  • sub - 表示要搜索的子字符串的字符串。

  • start - 可选整数,默认为 0。它表示搜索开始的左边缘索引。

  • end - 可选整数,默认为 None。它表示执行搜索的右边缘索引。

返回值

Series.str.find() 方法返回一个 Series 或索引,其中包含表示找到子字符串的最低索引的整数。如果未找到子字符串,则对于这些元素返回 -1。

示例 1

此示例演示了如何使用 Series.str.find() 方法在 Series 中每个字符串元素中查找子字符串的最低索引。

import pandas as pd

# Create a Series of strings
s = pd.Series(['python', ' Tutorialspoint', 'articles', 'Examples'])

# Find the index of the substring 'e' in each string
result = s.str.find('e')

print("Input Series:")
print(s)
print("\nIndexes of Substring 'e':")
print(result)

当我们运行以上代码时,它会产生以下输出:

Input Series:
0             python
1     Tutorialspoint
2           articles
3           Examples
dtype: object

Indexes of Substring 'e':
0   -1
1   -1
2    6
3    6
dtype: int64

示例 2

此示例演示了如何在 Series 中每个字符串元素的指定范围内查找子字符串的最低索引。

import pandas as pd

# Create a Series of strings
s = pd.Series(['python', ' Tutorialspoint', 'articles', 'Examples'])

# Find the index of the substring 't' within the range [2:10] in each string
result = s.str.find('t', start=2, end=10)

print("Input Series:")
print(s)
print("\nIndexes of Substring 't' within [2:10]:")
print(result)

当我们运行以上代码时,它会产生以下输出:

Input Series:
0             python
1     Tutorialspoint
2           articles
3           Examples
dtype: object

Indexes of Substring 't' within [2:10]:
0    2
1    3
2    2
3   -1
dtype: int64

指定的范围 [2:10] 用于限制在每个字符串元素中搜索子字符串 't'。

示例 3

此示例演示了当子字符串不在某些元素中时,如何在 Series 中每个字符串元素中查找子字符串的最低索引。

import pandas as pd

# Create a Series of strings
s = pd.Series(['python', 'Tutorialspoint', 'articles', 'Examples'])

# Find the index of the substring 'z' in each string
result = s.str.find('z')

print("Input Series:")
print(s)
print("\nIndexes of Substring 'z':")
print(result)

当我们运行以上代码时,它会产生以下输出:

Input Series:
0           python
1    Tutorialspoint
2         articles
3          Examples
dtype: object

Indexes of Substring 'z':
0   -1
1   -1
2   -1
3   -1
dtype: int64

所有元素的 -1 值表示子字符串 'z' 在任何字符串元素中都不存在。

python_pandas_working_with_text_data.htm
广告

© . All rights reserved.