gpt4 book ai didi

python - 将 Pandas 数据框中的值从字符串映射到 int(例如使用 Gender)

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:05 24 4
gpt4 key购买 nike

<分区>

我有一个名为 df_base 的 Dataframe,它看起来像这样。如您所见,有一个名为 Sex 的列,它是 malefemale。我想将这些值分别映射到 0 和 1。

+---+-------------+----------+--------+---------------------------------------------------+--------+-----+-------+-------+------------------+---------+-------+----------+
| | PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked |
+---+-------------+----------+--------+---------------------------------------------------+--------+-----+-------+-------+------------------+---------+-------+----------+
| 0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22 | 1 | 0 | A/5 21171 | 7.25 | NaN | S |
| 1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
| 2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26 | 0 | 0 | STON/O2. 3101282 | 7.925 | NaN | S |
| 3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35 | 1 | 0 | 113803 | 53.1 | C123 | S |
| 4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35 | 0 | 0 | 373450 | 8.05 | NaN | S |
+---+-------------+----------+--------+---------------------------------------------------+--------+-----+-------+-------+------------------+---------+-------+----------+

我在 StackOverflow 上看到了一些方法,但我想知道执行以下映射最有效的方法是什么:

+---------+---------+
| Old Sex | New Sex |
+---------+---------+
| male | 0 |
| female | 1 |
| female | 1 |
| female | 1 |
| male | 0 |
+---------+---------+

我正在使用这个:

df_base['性别'].replace(['男性','女性'],[0,1],inplace=True)

...但我不禁觉得这有点粗制滥造。有更好的方法吗?还有使用 .loc 但它会围绕 Dataframe 的行循环,所以效率较低,对吧?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com