Python Pandas Series.xs

Python Pandas Series.xs

Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据变得更加容易。

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

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

语法: Series.xs(key, axis=0, level=None, drop_level=True)

参数 :
key : 标签包含在索引中,或部分包含在多索引中。
axis:轴来检索横截面。
level : 如果一个键部分包含在一个多重索引中,请指出哪些级别被使用。级别可以通过标签或位置提及。
drop_level : 如果为假,返回与自己相同级别的对象。

返回:系列或数据框架

示例#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)

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

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

输出 :
Python Pandas Series.xs
正如我们在输出中看到的,Series.xs()函数已经返回了’里斯本’作为给定系列对象的横截面。

示例#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)

输出 :
Python Pandas Series.xs

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

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

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程