📜  Python|熊猫系列.xs

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

Python|熊猫系列.xs

Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。

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

Pandas Series.xs()函数返回给定键值的 Series/DataFrame 的横截面。

示例 #1:使用Series.xs()函数为传递的键值返回给定 Series 对象的横截面。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])
  
# Creating the row axis labels
sr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] 
  
# Print the series
print(sr)

输出 :

现在我们将使用Series.xs()函数返回给定系列对象的横截面。

# return cross-section corresponding to
# the 'City 4' label
sr.xs(key = 'City 4')

输出 :

正如我们在输出中看到的, Series.xs()函数返回了“里斯本”作为给定 Series 对象的横截面。示例 #2 :使用Dataframe.xs()函数为传递的键值返回给定 Dataframe 对象的横截面。

# importing pandas as pd
import pandas as pd
  
# Creating the Dataframe
df = pd.DataFrame({'num_legs': [4, 4, 2, 2],
                  'num_wings': [0, 0, 2, 2],
                  'class': ['Mammal', 'Mammal', 'Mammal', 'Bird'],
                  'animal': ['Cow', 'Elephant', 'Deer', 'Sparrow'],
                  'locomotion': ['Walks', 'Walks', 'Walks', 'Flies']})
  
# setting the index
df = df.set_index(['class', 'animal', 'locomotion'])
  
# Print the Dataframe
print(df)

输出 :

现在我们将使用Dataframe.xs()函数返回给定 Dataframe 对象的横截面。

# return cross-section corresponding to
# the 'Mammal' label
sr.xs(key = 'Mammal')

输出 :

正如我们在输出中看到的, Dataframe.xs()函数返回了给定 Dataframe 对象的横截面,用于传递的键值。