Pandas DataFrame ‘mask()’ Method.


Pandas DataFrame ‘mask( )’ Method.

Table Of Contents:

  1. Syntax Of ‘mask( )’ Method In Pandas.
  2. Examples ‘mask( )’ Method.

(1) Syntax:

DataFrame.mask(cond, other=nan, *, inplace=False, axis=None, 
               level=None, errors='raise', try_cast=_NoDefault.no_default)

Description:

  • Replace values where the condition is True.
  • Where cond is False, keep the original value.
  • Where True, replace with the corresponding value from other.

Parameters:

  • cond: bool Series/DataFrame, array-like, or callable – Where cond is False, keep the original value. Where True, replace with the corresponding value from other.
  • other: scalar, Series/DataFrame, or callable – Entries where cond is True are replaced with the corresponding value from other.
  • in place: bool, default False – Whether to perform the operation in place on the data.
  • axis: int, default None – Alignment axis if needed. For Series this parameter is unused and defaults to 0.
  • level: int, default None – Alignment level if needed.
  • errors: str, {‘raise’, ‘ignore’}, default ‘raise’ – Deprecated since version 1.5.0: This argument had no effect.
  • try_cast: bool, default None – Deprecated since version 1.3.0: Manually cast back if necessary.

Returns:

  • Same type as caller or None if inplace=True

(2) Examples Of mask() Method:

Example-1

import pandas as pd
student = {'Name':['Subrat','Abhispa','Arpita','Anuradha','Namita'],
          'Roll_No':[100,101,102,103,104],
          'Subject':['Math','English','Science','History','Commerce'],
          'Mark':[95,88,76,73,93]}
student_object = pd.DataFrame(student)
student_object

Output:

condition = (student_object['Gender'] == 'Female')
student_object.mask(condition)

Output:

Replacing With ‘#’:

student_object.mask(cond=condition,other='####')

Output:

Applying Multiple Conditions:

condition1 = (student_object['Gender'] == 'Female')
condition2 = (student_object['Mark'] > 90)
student_object.mask(condition1 & condition2)

Output:

Replacing With ‘@’:

student_object.mask(cond = condition1 & condition2, other='@@@@@@')

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *