python - 如何更改 Pandas 中多列的数据类型

标签 python pandas machine-learning jupyter-notebook random-forest

我正在尝试在 Pandas 数据帧上运行随机森林。我知道数据框中没有空值或无穷大,但在拟合模型时不断出现 ValueError。大概这是因为我有 flaot64 列而不是 float32;我还有很多 bool 和 int 类型的列。有没有办法将所有 float 列更改为 float32?

我已经尝试重写 CSV,并且相对确定问题不在于此。我以前在 float64s 上运行随机森林从来没有遇到过问题,所以我不确定这次出了什么问题。

labels = electric['electric_ratio']
electric = electric[[x for x in electric.columns if x != 'electric_ratio']]
electric_list = electric.columns
first_train, first_test, train_labels, test_labels = train_test_split(electric, labels)
rf = RandomForestRegressor(n_estimators = 1000, random_state=88)
rf_1 = rf.fit(first_train, train_labels)

我希望这符合模型,但始终如一

ValueError: Input contains NaN, infinity or a value too large for dtype('float32').

最佳答案

您可以将 df.astype() 与字典一起使用,以获取要使用相应数据类型更改的列。

df = df.astype({'col1': 'object', 'col2': 'int'})

关于python - 如何更改 Pandas 中多列的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55833729/

相关文章:

python - concurrent.futures.ThreadPoolExecutor.map 比 for 循环慢

python - 获取两个数组的行的有效方法,这些数组在其列的分数中具有匹配的值

Tensorflow 存储学习

machine-learning - 为卷积神经网络准备数据集

python - 获取 lxml/Python 中选定元素旁边的文本

python - 使用 Windows 的 PySpark 多列

python - 如何在完成解析之前退出模块?

python - 在 Pandas 中添加大小不均的数据列

python - 使用两个数据框计算最终值 pandas

python - Pytorch 的数据加载器 shuffle 何时发生?