Pandas DataFrame ‘where( )’ Method.
Table Of Contents:
- Syntax ‘where( )’ Method In Pandas.
- Examples ‘where( )’ Method.
(1) Syntax:
DataFrame.where(cond, other=_NoDefault.no_default, *, inplace=False, axis=None,
level=None, errors='raise', try_cast=_NoDefault.no_default)
Description:
- Return you the records where the condition satisfy.
- Replace values with ‘NaN’ where the condition is Not Satisfying.
- Where cond is True, keep the original value.
- Where False, replace with the corresponding value from other.
Parameters:
- cond: bool Series/DataFrame, array-like, or callable – Where cond is True, keep the original value. Where False, replace with the corresponding value from other.
- other: scalar, Series/DataFrame, or callable – Entries where cond is False 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 where() 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.where(condition)
Output:
Replacing With ‘#’:
student_object.where(cond=condition,other='####')
Output:
Applying Multiple Conditions:
condition1 = (student_object['Gender'] == 'Female')
condition2 = (student_object['Mark'] > 90)
student_object.where(condition1 & condition2)
Output:
Replacing With ‘@’:
student_object.where(cond = condition1 & condition2, other='@@@@@@')