Pandas Series.str.index() 方法



Python Pandas 中的Series.str.index()方法用于查找Series或DataFrame列中每个字符串中指定子字符串的第一次出现的位置。如果未找到子字符串,则会引发ValueError

此方法类似于标准 Python str.index()方法,它对字符串搜索操作很有用,确保显式处理缺失的子字符串。

语法

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

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

参数

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

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

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

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

返回值

Series.str.index()方法返回一个 Series 或 Index 对象,表示找到子字符串的最低索引。如果未找到子字符串,则会为这些元素引发ValueError

示例 1

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

import pandas as pd

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

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

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

运行上述代码时,会产生以下输出:

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

Indexes of Substring 'e':
0    2
1    2
2    2
dtype: int64

示例 2

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

import pandas as pd

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

# Find the index of the substring 't' within the range [2:10] 
result = s.str.index('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
dtype: object

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

示例 3

此示例演示了当子字符串不存在于某些元素中时Series.str.index()方法的行为,会引发ValueError

import pandas as pd

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

try:
    # Find the index of the substring 'z' in each string
    result = s.str.index('z')
    print("Indexes of Substring 'z':")
    print(result)
except ValueError as e:
    print(f"ValueError: {e}")

运行上述代码时,会产生以下输出:

ValueError: substring not found

引发ValueError是因为子字符串 'z' 不存在于任何字符串元素中。

python_pandas_working_with_text_data.htm
广告
© . All rights reserved.