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