找到并替换列中的数据

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