Python 如何在构建朴素贝叶斯模型中使用时间戳数据

How to use Timestamp Data in Building Naive Bayes model in Python

我有一个数据集,时间戳作为格式为 09/07/2016 23:58.

的列之一

我正在尝试对此数据应用朴素贝叶斯,但我遇到了以下错误。请让我知道如何在我的模型中使用这些数据

ValueError:float() 的无效文字:12/06/2016 23:59

您需要 to_datetime 和参数 errors='coerce' 才能将不可解析的错误值转换为 NaT:

df = pd.DataFrame({'date':['12/06/2016 23:59','12/06/2016 23:59', 'a']})
print (df)
               date
0  12/06/2016 23:59
1  12/06/2016 23:59
2                 a


print (pd.to_datetime(df.date, errors='coerce'))
0   2016-12-06 23:59:00
1   2016-12-06 23:59:00
2                   NaT
Name: date, dtype: datetime64[ns]

要测试错误值,请使用 boolean indexing - return 所有行,其中 NaT:

print (df[pd.to_datetime(df.date, errors='coerce').isnull()])
  date
2    a

从你的问题来看,你在做什么不是很清楚,但互联网上已经有几个例子:

SO 中的一些代码片段:

  • Unable to use Pandas and NLTK to train Naive Bayes (machine learning) in Python
  • How to run naive Bayes from NLTK with Python Pandas?