Open In App

How to find the Cross-section of Pandas Data frame?

Last Updated : 25 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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




# importing pandas library
import pandas as pd
  
# Creating a Dictionary
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']}
  
# Converting to Data frame and setting index
df = pd.DataFrame(data=animal_dict)
df = df.set_index(['class', 'animal', 'locomotion'])
  
# Displaying Data frame
df


Output:

Example 1: Getting values at a specific index

Python3




# Using dataframe.xs() function
# to get values of a specific index 
df.xs('Reptiles')


Output:

Example 2: Getting values at several indexes

Python3




# Using dataframe.xs() function
# to get values at several indexes 
df.xs(('Birds', 'Parrot'))


Output:

Example 3: Getting values at the specified index and level

Python3




# Using dataframe.xs() function
# to get values at specified index
# and level
df.xs('Crocodile', level = 1)


Output:

Example 4: Getting values at several indexes and levels

Python3




# Using dataframe.xs() function
# to get values at several indexes
# and levels
df.xs(('Birds', 'flies'),
      level=[0, 'locomotion'])


Output:

Example 5: Getting values at the specified column and axis

Python3




# Using dataframe.xs() function
# to get values at specified column
# and axis
df.xs('num_of_wings', axis=1)


Output:



Similar Reads

How to create a frame inside a frame tkinter?
Prerequisite: Tkinter It is very easy to create a basic frame using Tkinter, this article focuses on how another frame can be created within it. To create a basic frame the name of the parent window is given as the first parameter to the frame() function. Therefore, to add another frame within this frame, just the name of the first frame needs to g
2 min read
Add a new column in Pandas Data Frame Using a Dictionary
Pandas is basically the library in Python used for Data Analysis and Manipulation. To add a new Column in the data frame we have a variety of methods. But here in this post, we are discussing adding a new column by using the dictionary. Let's take Example! # Python program to illustrate # Add a new column in Pandas # Importing the pandas Library im
2 min read
Python Program to perform cross join in Pandas
In Pandas, there are parameters to perform left, right, inner or outer merge and join on two DataFrames or Series. However there's no possibility as of now to perform a cross join to merge or join two methods using how="cross" parameter. Cross Join : Example 1: The above example is proven as follows # importing pandas module import pandas as pd # D
3 min read
Rendering Data-Frame to html template in table view using Django Framework
In Django, It is easy to render the HTML templates by setting URLs of respective HTML pages. Here we will let to know about how we can work with DataFrame to modify them for table view in the HTML template or web-pages, and for that, we have to use 'render' and 'HttpResponse' functions to manipulate the data inside the DataFrame. Sample DataFrame:
3 min read
Extract Dictionary Value from Column in Data Frame
Data Frames in Python, especially with libraries like Pandas, are powerful tools for data manipulation and analysis. Sometimes, data stored within a Data Frame's column may be in the form of dictionaries. Extracting values from such dictionaries is a common operation in data preprocessing. This post explores various methods to extract dictionary va
3 min read
Pandas Series dt.weekday | Find Day of the Week in Pandas
The dt.weekday attribute returns the day of the week. It is assumed the week starts on Monday, which is denoted by 0, and ends on Sunday which is denoted by 6. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day
2 min read
How to make a proper double scrollbar frame in Tkinter
Tkinter is a Python binding to the Tk GUI(Graphical User Interface) Toolkit. It is a thin-object oriented layer on top of Tcl/Tk. When combined with Python, it helps create fast and efficient GUI applications. Note: For more information refer, Python GUI-tkinter Steps to Create a double scrollbar frame in Tkinter 1) Firstly, the module Tkinter will
3 min read
PyQt5 - Checking if the Combo box is having frame or not
In this article we will see how we can find if the combo box is having frame or not. By default when we create a combo box it has frame although we can change it. In order to check if frame exist or not we use hasFrame method. Syntax : combo_box.hasFrame() Argument : It takes no argument Return : It returns bool Below is the implementation - # impo
2 min read
PyQt5 - Setting/Disabling the frame of ComboBox
In this article we will see how we can set or disable the frame of the combo box. By default when we create a combo box it has frame although we can change it. In order to set or disable frame we use setFrame method. Syntax : combo_box.setFrame(False) Argument : It takes bool as argument Action performed : It will disable the frame of check box Bel
2 min read
wxPython - Frame() Constructor in Python
In this article we will know about the frame() constructor in wxPython. frame() constructor is a constructor for the wx.Frame class of wxPython. This constructor is used to set different attributes of the frame. Syntax : wx.Frame(parent, id=ID_ANY, title="", pos=DefaultPosition, size=DefaultSize, style=DEFAULT_FRAME_STYLE, name=FrameNameStr) Parame
1 min read