The Wayback Machine - https://web.archive.org/web/20240912153556/https://www.geeksforgeeks.org/python-pandas-dataframe-mask/
Open In App

Python | Pandas dataframe.mask()

Last Updated : 19 Nov, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas dataframe.mask() function return an object of same shape as self and whose corresponding entries are from self where cond is False and otherwise are from other object. The other object could be a scalar, series, dataframe or could be a callable. The mask method is an application of the if-then idiom. For each element in the calling DataFrame, if cond is False the element is used; otherwise the corresponding element from the DataFrame other is used.

Syntax: DataFrame.mask(cond, other=nan, inplace=False, axis=None, level=None, errors=’raise’, try_cast=False, raise_on_error=None)

Parameters :
cond : Where cond is False, keep the original value. Where True, replace with corresponding value from other. If cond is callable, it is computed on the NDFrame and should return boolean NDFrame or array. The callable must not change input NDFrame (though pandas doesn’t check it).

other : Entries where cond is True are replaced with corresponding value from other. If other is callable, it is computed on the NDFrame and should return scalar or NDFrame. The callable must not change input NDFrame (though pandas doesn’t check it).
inplace : Whether to perform the operation in place on the data
axis : alignment axis if needed, default None
level : alignment level if needed, default None
errors : str, {‘raise’, ‘ignore’}, default ‘raise’
raise allow exceptions to be raised and ignore suppress exceptions. On error return original object. Note that currently this parameter won’t affect the results and will always coerce to a suitable dtype.

try_cast : try to cast the result back to the input type (if possible),

Returns : wh : same type as caller

Example #1: Use mask() function to replace all the values in the dataframe which are greater than 10 with -25





Let’s use the dataframe.mask() function to replace all the values greater than 10 with -25





Output :

 

Example #2: Use mask() function with a callable. Replace all the Na value with 1000.





Output :



Previous Article
Next Article

Similar Reads

Python | Pandas Series.mask()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.mask() function is used for masking purpose. This function replace values where
2 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
How to mask an array using another array in Python ?
In this article, we will learn how to mask an array using another array in Python. When working with data arrays or data-frames masking can be extremely useful. Masks are an array that contains the list of boolean values for the given condition. The masked array is the arrays that have invalid or missing entries. Using Masking of arrays we can easi
7 min read
PyQt5 QSpinBox - Clearing the Mask
In this article we will see how we can clear the mask from the spin box, masks are used to hide part of a UI Image element. We can set mask using setMask method. In order to do this we use clearMask method. Syntax : spin_box.clearMask() Argument : It takes no argument Action Performed : It mask on the spin box Implementation steps : 1. Create a mai
2 min read
PyQt5 QSpinBox - How to set Mask
In this article we will see how we can set the mask to the spin box, mask are basically used to hide the spin box, with the help of mask user will not be able to see the whole spin box although the spin box will still exist but there will be mask on it. In order to do this we use setMask method. Syntax : spin_box.setMask(region) Argument : It takes
2 min read
PyQt5 QSpinBox - Getting the Mask
In this article we will see how we can get the mask of the spin box, mask are basically used to hide the spin box, with the help of mask user will not be able to see the whole spin box although the spin box will still exist but there will be mask on it. Mask can be set to the spin box with the help of setMask method. In order to get the mask we use
2 min read
PyQt5 QCalendarWidget - Setting Mask
In this article we will see how we can set the mask to the QCalendarWidget. Mask are basically used to hide the calendar, with the help of mask user will not be able to see the whole calendar although the calendar will still exist but there will be mask on it. It causes only the pixels of the calendar for which bitmap has a corresponding 1 bit to b
2 min read
PyQt5 QCalendarWidget - Getting Mask
In this article we will see how we can get the mask of the QCalendarWidget. Mask are basically used to hide the calendar, with the help of mask user will not be able to see the whole calendar although the calendar will still exist but there will be mask on it.We can set mask to the calendar with the help of setMask method. In order to do this we wi
2 min read
PyQt5 QCalendarWidget - Removing the Mask
In this article we will see how we can remove i.e clear the mask of the QCalendarWidget. Mask are basically used to hide the calendar, with the help of mask user will not be able to see the whole calendar although the calendar will still exist but there will be mask on it.We can set mask to the calendar with the help of setMask method. In order to
2 min read
MoviePy – Checking Mask of Video File Clip
In this article we will see how we can check if the video file clip in MoviePy is a mask video or not. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. IsMask property tells that if the given video clip is mask or not, mask is basically that video which is used as mask for the another video.
2 min read
MoviePy – Adding Mask to Video File Clip
In this article we will see how we can add mask to the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. IsMask property tells that if the given video clip is mask or not, mask is basically that video which is used as mask for the another video. We can make a video
2 min read
PyQtGraph – Getting Mask of Image View
In this article, we will see how we can get a mask of the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widget used
4 min read
PyQtGraph – Removing Mask of Image View
In this article, we will see how we can remove the mask of the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widget
4 min read
PyQtGraph – Setting Mask to Image View
In this article, we will see how we can set the mask to the image view object in PyQTGraph. The PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widge
4 min read
OpenCV - Invert Mask
In this article, we will learn how to invert a mask created on an image in OpenCV. Masking is a technique used to highlight a specific object from the image. It can be defined as setting certain pixels of an image to some null value such as 0 (black color) so only that portion of our image is highlighted where the pixel value is not 0. Inverting a
4 min read
Filter Pandas dataframe in Python using 'in' and 'not in'
The in and not in operators can be used with Pandas DataFrames to check if a given value or set of values is present in the DataFrame or not using Python. The in-operator returns a boolean value indicating whether the specified value is present in the DataFrame, while the not-in-operator returns a boolean value indicating whether the specified valu
3 min read
Python | Pandas DataFrame.reset_index()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas reset_index() is a method to reset index of a Data Frame. reset_index() method sets a list of integer ranging from 0 to length of
2 min read