How to find the Cross-section of Pandas Data frame?
Last Updated :
25 Oct, 2020
Sometimes we need to find the cross-section of pandas series or data frame. Here cross-section means getting values at the specified index, values at several indexes, values at several indexes and levels or values at the specified column and axis etc. There is a function known as pandas.DataFrame.xs() which will help in this condition.
pandas.DataFrame.xs() takes a key argument in order to select data at the particular level in MultiIndex and returns cross-section from pandas data frame.
Syntax: DataFrame.xs(key, axis=0, level=None, drop_level=True)
Parameters:
key – Label contained in the index, or partially in a MultiIndex.
axis – Axis to retrieve cross-section on.
level – In case of a key partially contained in a MultiIndex, indicate which levels are used.
drop_level – If False, returns an object with the same levels as self.
Returns:
Cross-section from the original DataFrame
Below is the pandas code which will help in the proper understanding of pandas.DataFrame.xs() function.
Python3
import pandas as pd
animal_dict = { 'num_of_legs' : [ 4 , 0 , 4 , 2 , 2 , 2 ],
'num_of_wings' : [ 0 , 0 , 0 , 2 , 2 , 2 ],
'class' : [ 'Reptiles' , 'Reptiles' , 'Reptiles' ,
'Birds' , 'Birds' , 'Birds' ],
'animal' : [ 'Turtle' , 'Snake' , 'Crocodile' ,
'Parrot' , 'Owl' , 'Hummingbird' ],
'locomotion' : [ 'swim_walk' , 'swim_crawl' , 'swim_walk' ,
'flies' , 'flies' , 'flies' ]}
df = pd.DataFrame(data = animal_dict)
df = df.set_index([ 'class' , 'animal' , 'locomotion' ])
df
|
Output:
Example 1: Getting values at a specific index
Output:
Example 2: Getting values at several indexes
Python3
df.xs(( 'Birds' , 'Parrot' ))
|
Output:
Example 3: Getting values at the specified index and level
Python3
df.xs( 'Crocodile' , level = 1 )
|
Output:
Example 4: Getting values at several indexes and levels
Python3
df.xs(( 'Birds' , 'flies' ),
level = [ 0 , 'locomotion' ])
|
Output:
Example 5: Getting values at the specified column and axis
Python3
df.xs( 'num_of_wings' , axis = 1 )
|
Output:
Share your thoughts in the comments
Please Login to comment...