Python | Pandas Series.loc
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 series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.loc attribute is used to access a group of rows and columns by label(s) or a boolean array in the given Series object.
Syntax:Series.loc
Parameter : None
Returns : series
Example #1: Use Series.loc attribute to select some values from the given Series object based on the labels.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr) |
Output :

Now we will use Series.loc attribute to return the values of the selected labels in the given Series object.
# return the selected values.sr.loc[['City 4', 'City 3', 'City 1']] |
Output :

As we can see in the output, the Series.loc attribute has returned the name of the cities whose labels were passed to it.
Example #2 : Use Series.loc attribute to select some values from the given Series object based on the labels.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr) |
Output :

Now we will use Series.loc attribute to return the values of the selected labels in the given Series object.
# return the selected values.sr.loc[['Day 4', 'Day 3', 'Day 1']] |
Output :
As we can see in the output, the Series.loc attribute has returned the name of the cities whose labels were passed to it.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


