gpt4 book ai didi

python - Scikit-learn 中仅针对 DataFrame 的一部分进行 One-Hot 编码

转载 作者:行者123 更新时间:2023-11-30 08:56:56 26 4
gpt4 key购买 nike

我正在尝试对我的数据使用决策树分类器,它看起来与本教程中的数据非常相似:https://www.ritchieng.com/machinelearning-one-hot-encoding/ enter image description here

教程然后继续将字符串转换为数字数据:

X = pd.read_csv('titanic_data.csv')
X = X.select_dtypes(include=[object])
le = preprocessing.LabelEncoder()
X_2 = X.apply(le.fit_transform)

这使得 DataFrame 看起来像这样:

enter image description here

此后,数据将通过 OneHotEncoder,我认为然后可以相当容易地拆分并传递到决策树分类器中。

问题是,在我看来,原始数字数据通过这个编码过程获得了很多。如何保留或添加在编码过程中删除的数字数据?谢谢!

最佳答案

实际上有一个非常简单的解决方案 - 使用 pd.get_dummies()

如果您有如下所示的数据框:

so_data = {
'passenger_id': [1,2,3,4,5],
'survived': [1,0,0,1,0],
'age': [24,25,68,39,5],
'sex': ['female', 'male', 'male', 'female', 'female'],
'first_name': ['Joanne', 'Mark', 'Josh', 'Petka', 'Ariel']
}
so_df = pd.DataFrame(so_data)

看起来像:

    passenger_id    survived    age   sex       first_name
0 1 1 24 female Joanne
1 2 0 25 male Mark
2 3 0 68 male Josh
3 4 1 39 female Petka
4 5 0 5 female Ariel

你可以这样做:

pd.get_dummies(so_df)

这会给你:

enter image description here

(抱歉截图,但是清理 df 真的很难)

关于python - Scikit-learn 中仅针对 DataFrame 的一部分进行 One-Hot 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56584288/

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