【问题标题】:How to change datatype of multiple columns in pandas如何更改熊猫中多列的数据类型
【发布时间】:2019-09-13 23:13:46
【问题描述】:

我正在尝试在 pandas 数据帧上运行随机森林。我知道数据框中没有空值或无穷大,但是当我拟合模型时会不断收到 ValueError 。大概这是因为我有 flot64 列而不是 float32;我也有很多 bool 和 int 类型的列。有没有办法把所有的浮动列都改成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').

【问题讨论】:

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


【解决方案1】:

您可以使用.astype() method 为任何pandas 对象转换数据类型。

例子:

x = pd.DataFrame({'col1':[True, False, True], 'col2':[1, 2, 3], 'col3': [float('nan'), 0, None] })
x = x.astype('float32')
print(x)

Out[2]: 
   col1  col2  col3
0   1.0   1.0   NaN
1   0.0   2.0   0.0
2   1.0   3.0   NaN

然后您需要使用 .fillna() 文档处理任何 NaN 值,因为这是 here

x = x.fillna(0)
Out[3]: 
   col1  col2  col3
0   1.0   1.0   0.0
1   0.0   2.0   0.0
2   1.0   3.0   0.0

【讨论】:

    【解决方案2】:

    要将所有 float64 列的 dtypes 更改为 float32 列,请尝试以下操作:

    for column in df.columns:
        if df[column].dtype == 'float64':
            df[column] = df[column].astype(np.float32)
    

    【讨论】:

      【解决方案3】:

      您可以将 df.astype() 与字典一起使用,以便使用相应的 dtype 更改要更改的列。

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

      【讨论】:

        猜你喜欢
        • 2013-03-31
        • 2021-07-31
        相关资源
        最近更新 更多