Open In App

Python | Pandas Index.slice_locs()

Last Updated : 18 Dec, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas Index.slice_locs() function compute slice locations for input labels. It takes start and end labels as the parameter and returns the integer value corresponding to those values.

Syntax: Index.slice_locs(start=None, end=None, step=None, kind=None)

Parameters :
start : If None, defaults to the beginning
end : If None, defaults to the end
step : If None, defaults to 1
kind : {‘ix’, ‘loc’, ‘getitem’} or None

Returns : start, end : int

Example #1: Use Index.slice_locs() function to find the slice labels for the input values.




# importing pandas as pd
import pandas as pd
  
# Creating the index 
idx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Sephard',
                             'Mastiff', None, 'Husky'])
  
# Print the index
idx


Output :

Now we will find the slice labels for ‘Pug’ and ‘Mastiff’




# finding the slice labels for the input value.
idx.slice_locs(start ='Pug', end ='Mastiff')


Output :

As we can see in the output, the function has returned the slice locations for the input labels.
 
Example #2: Use Index.slice_locs() function to find the slice labels in the date-time base index.




# importing pandas as pd
import pandas as pd
  
# Creating the index 
idx = pd.date_range('1 / 1/2018', periods = 5, freq ='MS')
  
# Print the index
idx


Output :

Now we would find the slice labels for the input labels.




# finding the slice labels
idx.slice_locs(start ='2018-02-01', end ='2018-04-01')


Output :

As we can see in the output, the function has returned the range values which contains the input slice label value.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads