我正在尝试在熊猫数据帧上运行随机森林。我知道数据帧中没有空值或无穷大但在我适合模型时不断得到ValueError。大概这是因为我有flaot64列而不是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').
要将所有float64列的dtypes更改为float32列,请尝试以下操作:
for column in df.columns:
if df[column].dtype == 'float64':
df[column] = df[column].astype(np.float32)
您可以将.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