Replacing Values in a DataFrame Column

Write a Pandas program to replace the ‘qualify’ column contains the values ‘yes’ and ‘no’ with True and False.

Example 1:

Input: DataFrame with 'qualify' column values as 'yes' and 'no' 
Output: DataFrame with 'qualify' column values as True and False

Example 2:

Input: DataFrame with 'qualify' column values as 'yes' and 'no' 
Output: DataFrame with 'qualify' column values as True and False

Use the pandas replace() function.

import pandas as pd

def replace_values(df):
    df['qualify'] = df['qualify'].replace({'yes': True, 'no': False})
    return df

df1 = pd.DataFrame({'name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'qualify': ['yes', 'no', 'yes', 'no']})
df2 = pd.DataFrame({'name': ['Adam', 'Eve', 'Stark', 'Rogers'], 'qualify': ['no', 'yes', 'no', 'yes']})

print(replace_values(df1))
print(replace_values(df2))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!