📅  最后修改于: 2023-12-03 15:04:22.014000             🧑  作者: Mango
The Series.str.index()
method in Pandas is used to find the lowest first occurrence index of a specified substring in each element of the Series. This method returns -1 if the substring is not found in any element of the Series.
Series.str.index(sub, start=0, end=len(string))
The method returns a Series containing the lowest first occurrence index of the specified substring in each element. If the substring is not found, it returns -1.
Let's consider a Pandas Series containing names of fruits:
import pandas as pd
data = {'fruits': ['apple', 'banana', 'orange', 'grape']}
series = pd.Series(data['fruits'])
sub_string = 'an'
result = series.str.index(sub_string)
print(result)
Output:
0 1
1 1
2 -1
3 2
dtype: int64
start_index = 2
end_index = 5
sub_string = 'phon'
result = series.str.index(sub_string, start=start_index, end=end_index)
print(result)
Output:
0 -1
1 -1
2 -1
3 -1
dtype: int64
In example 1, the method finds the lowest first occurrence index of 'an' in each element of the Series. The result is a new Series where the first element has index 1, the second element has index 1, the third element does not have 'an' and the fourth element has index 2.
In example 2, the method tries to find 'phon' in the range from index 2 to 5 in each element. As 'phon' is not present in any of the elements, the returned Series contains -1 in all the positions.