Python 如何更改pandas中多个列的数据类型
我试图在熊猫数据帧上运行一个随机林。我知道数据帧中没有空值或无穷大,但当我拟合模型时,会不断得到一个ValueError。这大概是因为我有flaot64列而不是float32列;我还有很多bool和int类型的列。有没有办法把所有的float列都改成float32 我尝试过重写CSV,并且相对确定问题不在于此。我以前在浮动64上运行随机森林从来没有遇到过问题,所以我不确定这次出了什么问题Python 如何更改pandas中多个列的数据类型,python,pandas,machine-learning,jupyter-notebook,random-forest,Python,Pandas,Machine Learning,Jupyter Notebook,Random Forest,我试图在熊猫数据帧上运行一个随机林。我知道数据帧中没有空值或无穷大,但当我拟合模型时,会不断得到一个ValueError。这大概是因为我有flaot64列而不是float32列;我还有很多bool和int类型的列。有没有办法把所有的float列都改成float32 我尝试过重写CSV,并且相对确定问题不在于此。我以前在浮动64上运行随机森林从来没有遇到过问题,所以我不确定这次出了什么问题 labels = electric['electric_ratio'] electric = electri
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').
您可以对任何对象使用.astype()
来转换数据类型
例如:
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值
要将所有float64列的数据类型更改为float32列,请尝试以下操作:
for column in df.columns:
if df[column].dtype == 'float64':
df[column] = df[column].astype(np.float32)
可能重复的
for column in df.columns:
if df[column].dtype == 'float64':
df[column] = df[column].astype(np.float32)