'How to remake this code for dataframe mapping properly

titset["Sex"] = titset["Sex"].map({"male": 2, "female": 1})
titset["Embarked"] = titset["Embarked"].map({"S": 1, "C": 2, 'Q' : 3})

I had such code but i was told that i can't use it because it have been already used so i'm confused how to remake it remake it to have the same functionality as it has. It changes 'male' in Sex column and 'female' values on 2 and 1, and on 'Embarked' column in replaces 'S' with 1 etc



Solution 1:[1]

I think I answer your other, very similar question. If this is homework and you must do the replacement in different ways:

# Assuming there are only 2 sexes
titset["Sex"] = np.where(titset["Sex"] == "female", 1, 2)

# If more than 2 sexes
titset["Sex"] = np.select(
    [
        titset["Sex"] == "female",
        titset["Sex"] == "male",
        titset["Sex"] == "other",
    ],
    [
        1,
        2,
        3
    ]
)

# You can also use a plain old loop
# (slow, not recommended)
new_sex = []
for sex in titset["Sex"]:
    if sex == "female":
        new_sex.append(1)
    elif sex == "male":
        new_sex.append(2)
    elif sex == "other":
        new_sex.append(3)
titset["Sex"] = new_sex

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Code Different