📜  Python|熊猫 Series.select()

📅  最后修改于: 2022-05-13 01:54:51.038000             🧑  作者: Mango

Python|熊猫 Series.select()

Pandas 系列是带有轴标签的一维 ndarray。标签不必是唯一的,但必须是可散列的类型。该对象支持基于整数和基于标签的索引,并提供了许多用于执行涉及索引的操作的方法。

Pandas Series.select()函数返回与匹配条件的轴标签对应的数据。我们将函数名称作为参数传递给该函数,该函数应用于所有索引标签。选择满足条件的索引标签。

示例 #1:使用Series.select()函数从给定的 Series 对象中选择所有城市的名称,其索引标签甚至结束。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])
  
# Create the Datetime Index
index_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6']
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

输出 :

现在我们将使用Series.select()函数来选择所有这些城市的名称,其索引标签以偶数值结尾。

# Define a function to  Select those cities whose index
# label's last character is an even integer
def city_even(city):
    # if last character is even
    if int(city[-1]) % 2 == 0:
        return True
    else:
        return False
  
# Call the function and select the values
selected_cities = sr.select(city_even, axis = 0)
  
# Print the returned Series object
print(selected_cities)

输出 :

正如我们在输出中看到的, Series.select()函数已成功返回所有满足给定条件的城市。

示例 #2:使用Series.select()函数从给定的 Series 对象中选择“可口可乐”和“雪碧”的销售额。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([100, 25, 32, 118, 24, 65])
  
# Create the Index
index_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

输出 :

现在我们将使用Series.select()函数从给定的 Series 对象中选择列出的饮料的销售额。

# Function to select the sales of 
# Coca Cola and Sprite
def show_sales(x):
    if x == 'Sprite' or x == 'Coca Cola':
        return True
    else:
        return False
  
# Call the function and select the values
selected_cities = sr.select(show_sales, axis = 0)
  
# Print the returned Series object
print(selected_cities)

输出 :

正如我们在输出中看到的, Series.select()函数已经成功地从给定的 Series 对象返回了所需饮料的销售数据。