找到並替換列中的資料

import pandas as pd

df = pd.DataFrame({'gender': ["male", "female","female"],
                    'id': [1, 2, 3] })
>>> df
   gender  id
0    male   1
1  female   2
2  female   3

要將男性編碼為 0,將女性編碼為 1:

df.loc[df["gender"] == "male","gender"] = 0
df.loc[df["gender"] == "female","gender"] = 1

>>> df
       gender  id
    0       0   1
    1       1   2
    2       1   3