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
廣告