Home > Enterprise >  Pandas if-else condition
Pandas if-else condition

Time:03-24

I am just trying on with Pandas and am not sure why I am not getting the proper output (titanic dataset from seaborn).

Status columns should show "f" where it says female in column "sex". (Image Attached)

The picture of the dataframe

CodePudding user response:

A good solution has been provided by @Phoenix based on what you have tried so far. But in the case of an if-else condition, you can use numpy.where function too:

import numpy as np
data["Status"] = np.where(data["sex"] == "female", "f", "m")

CodePudding user response:

The mistake is in the assignment data['Status'] = 'm'. You set all values of this column to m. To correct this, you can iterate through the column using:

for index in range(data.shape[0]):
    if data.loc[index,'sex'] == 'male': 
        data.loc[index,'Status'] = 'm'
    else:
        data.loc[index,'Status'] = 'f'

There is another solution:

dict_val = {'female': 'f', 'male': 'm'}
df['status'] = df['sex'].map(values_dict)
  • Related