将数据中的性别列对应的男女替换成1和0,并做成新的列。
In [1]: importpandas as pd
...: d ={"gender":["male", "female","male","female"],
...: "color":["red","green", "blue","green"],
...: "age":[25, 30, 15, 32] }
...:
...: df =pd.DataFrame(d)
...: df
Out[1]:
gender color age
0 male red 25
1 female green 30
2 male blue 15
3 female green 32
在 gender 列上,使用 map 方法,快速完成如下映射:
In [2]: d ={"male": 0, "female": 1}
...:df["gender2"] = df["gender"].map(d)
In [3]: df
Out[3]:
gender color age gender2
0 male red 25 0
1 female green 30 1
2 male blue 15 0
3 female green 32 1
也可以通过apply来实现
In [4]:df["mal_n"]=df.gender.apply(lambda x:1 ifx=="male" else 0)
df
Out[4]:
gender color age mal_n
0 male red 25 1
1 female green 30 0
2 male blue 15 1
3 female green 32 0
还可以输入200个字
蝈蝈派【海南省教改项目(Hnjg2022-80)支持】 网站版权所有
Python remained the copyright of our website