以色列邻居

2024-05-15 23:05:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了一个错误,不太清楚为什么会这样…这是我的数据看起来像这样的一点

    Date/Time            Lat        Lon      Base
0   8/1/2014 0:03:00    40.7366 -73.9906    B02512
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing 

df = pd.read_csv('aug.csv')
df.head()
X = df.drop(columns =['Base'])
clus = df[['Lat','Lon']]
y = clus 

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=1)

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors = 1)

knn.fit(X_train,y_train)

 #Here is my error from the knn.fit(X_train,y_train)
 ValueError: could not convert string to float: '8/11/2014 7:33:00'

Tags: csvfromtestimportdfbaseastrain
1条回答
网友
1楼 · 发布于 2024-05-15 23:05:45

数据中的日期/时间列是字符串类型。KNN分类器期望输入数据是数字的,因此 ValueError: could not convert string to float: '8/11/2014 7:33:00'当它尝试将字符串转换为浮点时

将日期字符串转换为数字数据类型的策略很少

如果您的Date/Time列在性质上是categoricalcategories,那么您可以尝试one-hot-encoding

或者,如果该列没有为您的分析提供任何有意义的信息,您可以简单地drop该列

或者您可以使用此函数将date/time列转换为总秒数

pd.to_timedelta(df.date).dt.total_seconds()

其中pd是pandas,dfDataFrame对象

注意:此代码要求输入为特定类型。对于日期字符串,您应该尝试以下操作:

df['Date/Time'] = df['Date/Time'].astype('datetime64').astype(int).astype(float)

始终注意:统计建模技术适用于数值数据。您必须找到一种方法将所有输入转换为数字类型

相关问题 更多 >