[英]Replace specific entries in a column of dataframe
我想将“性别”列中的所有“男性”替换为1 ,将所有“女性”替换为0 。
这是我的 dataframe df :
Pclass Sex Age SibSp Parch
0 3 male 22.0 1 0
1 1 female 38.0 1 0
2 3 female 26.0 0 0
3 1 female 35.0 1 0
4 3 male 35.0 0 0
5 3 male 2.0 3 1
6 3 female 27.0 0 2
7 2 female 14.0 1 0
8 3 female 4.0 1 1
9 1 female 58.0 0 0
我使用了pd.get_dummies
:
pd.get_dummies(df.Sex)
但它会像这样创建两列男性和女性:
female male
0 0 1
1 1 0
2 1 0
3 1 0
4 0 1
另一方面,我只想要一列性别,表示1 为 male , 0 为 female 。
我知道我可以使用 for 循环来遍历所有行并进行更改,但是有没有一种可取的方法来做到这一点?
试试下面的代码:
df["Sex"].replace({"male": 1, "female": 0}, inplace=True)
与==
比较,然后将boolean
类型结果转换为int
类型。
df['Sex_'] = (df.Sex == 'male').astype(int)
或者如果你想使用你当前的代码pd.get_dummies
你可以删除一列
df['Sex_'] = pd.get_dummies(df.Sex, drop_first = True)
如果需要map
很多标签,试试:
dicts = {"male":1,"female":0}
df['Sex'].map(dicts)
请确保df['Sex'].value_counts()
的 'Sex' 列只有 'male' & 'female' 值 如果是这样的话
df['Sex'] = df['Sex'].apply(lambda x:1 if x == 'male' else 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.