Pandas DataFrame:无法将字符串列(?)转换为Int

时间:2017-06-23 17:34:17

标签: python pandas dataframe

我正在运行一些机器学习代码,要求我的Pandas DataFrame中的值为数字(浮点数,整数等)。它看起来像这样(X是训练集,Y是目标向量):

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
lin_reg = LinearRegression()
lin_reg.fit(X, Y)
views_predictions = lin_reg.predict(X)
lin_mse = mean_squared_error(Y, views_predictions)
lin_rmse = np.sqrt(lin_mse)
lin_rmse

但是,尝试运行时出现此错误:

ValueError: could not convert string to float: original

所以,我检查了我的DataFrame的dtype,看到我的type列是一个对象,而不是一个字符串......

我试过这个来解决这个问题:

final_df['type'] = (final_df['type'] == 'licensed').astype(int)

不幸的是,我收到一个奇怪的类型错误:

TypeError: Could not compare ['licensed'] with block values

不确定如何解释或解决问题。

有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

< p>您的示例使其看起来好像您正在尝试将实际单词转换为整数,而不仅仅是存储为字符串的数字。< / p> < p>通常在sklearn模型中使用字符串,您需要将字符串映射到占位符整数值。尝试使用如下地图:< / p> < pre>< code> type_map = {value:i for i,value in enumerate(list(final_df [' type']。unique()))} final_df [' type_int'] = final_df [' type']。map(value_map) < /代码>< /预> < p>现在删除原始< code> final_df [' type']< / code>列,并使用< code> final_df [' type_int']< / code>而是为了你的计算。< / p>
相关问题