我得到了一个错误,不太确定为什么会这样……这是我的数据看起来像这个的一点
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'
数据中的日期/时间列是字符串类型。KNN分类器期望输入数据是数字的,因此尝试将字符串转换为浮动时的ValueError: could not convert string to float: '8/11/2014 7:33:00'
将日期字符串转换为数字数据类型的策略很少。
如果你的Date/Time
列本质上是categorical
,很少有categories
,你可以试试one-hot-encoding
。
或者,如果列没有为您的分析提供任何有意义的信息,您可以简单地drop
列。
也可以使用此方法将date/time
列转换为总秒数。
pd.to_timedelta(df.date).dt.total_seconds()
其中pd
是熊猫,df
是您的DataFrame
对象。
注意:此代码要求输入为特定类型。对于您的日期字符串,您应该尝试以下操作:
df['Date/Time'] = df['Date/Time'].astype('datetime64').astype(int).astype(float)
请注意:统计建模技术适用于数字数据。你必须找到一种方法将所有输入转换为数字类型