Python | Pandas Series.select()
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.select()
function return data corresponding to axis labels matching criteria. We pass the name of the function as an argument to this function which is applied on all the index labels. The index labels satisfying the criteria are selected.
Syntax: Series.select(crit, axis=0)
Parameter :
crit : called on each index (label). Should return True or False
axis : int value
Returns : selection : same type as caller
Example #1: Use Series.select()
function to select the names of all those cities from the given Series object for which it’s index labels has even ending.
import pandas as pd
sr = pd.Series([ 'New York' , 'Chicago' , 'Toronto' , 'Lisbon' , 'Rio' , 'Moscow' ])
index_ = [ 'City 1' , 'City 2' , 'City 3' , 'City 4' , 'City 5' , 'City 6' ]
sr.index = index_
print (sr)
|
Output :
Now we will use Series.select()
function to select the names of all those cities, whose index label ends with even integer value.
def city_even(city):
if int (city[ - 1 ]) % 2 = = 0 :
return True
else :
return False
selected_cities = sr.select(city_even, axis = 0 )
print (selected_cities)
|
Output :
As we can see in the output, the Series.select()
function has successfully returned all those cities which satisfies the given criteria.
Example #2: Use Series.select()
function to select the sales of the ‘Coca Cola’ and ‘Sprite’ from the given Series object.
import pandas as pd
sr = pd.Series([ 100 , 25 , 32 , 118 , 24 , 65 ])
index_ = [ 'Coca Cola' , 'Sprite' , 'Coke' , 'Fanta' , 'Dew' , 'ThumbsUp' ]
sr.index = index_
print (sr)
|
Output :
Now we will use Series.select()
function to select the sales of the listed beverages from the given Series object.
def show_sales(x):
if x = = 'Sprite' or x = = 'Coca Cola' :
return True
else :
return False
selected_cities = sr.select(show_sales, axis = 0 )
print (selected_cities)
|
Output :
As we can see in the output, the Series.select()
function has successfully returned the sales data of the desired beverages from the given Series object.
Last Updated :
07 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...