【问题标题】:KNearest NeighborK 最近邻
【发布时间】:2020-12-06 03:09:03
【问题描述】:

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

    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'

【问题讨论】:

    标签: python pandas knn


    【解决方案1】:

    数据中的日期/时间列是字符串类型。 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 是 pandas,df 是您的 DataFrame 对象。

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

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

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

    【讨论】:

    • 如果我删除该列,我现在会收到与 Base 列相同的错误...
    猜你喜欢
    • 1970-01-01
    • 2014-04-12
    • 2018-04-08
    • 2014-05-14
    • 2011-12-06
    • 1970-01-01
    • 2013-03-21
    • 2014-05-12
    • 1970-01-01
    相关资源
    最近更新 更多