【问题标题】:Invalid comparison between dtype=datetime64[ns] and datedtype=datetime64[ns] 和日期之间的无效比较
【发布时间】:2020-05-14 19:43:03
【问题描述】:

我正在尝试解决我在这里面临的这个问题。

#import libraries
from __future__ import division
from datetime import datetime, timedelta,date
import pandas as pd
%matplotlib inline
from sklearn.metrics import classification_report,confusion_matrix
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.cluster import KMeans

import plotly.offline as pyoff
import plotly.graph_objs as go

from sklearn.model_selection import KFold, cross_val_score, train_test_split

#initate plotly
pyoff.init_notebook_mode()

#read data from csv and redo the data work we done before
tx_data = pd.read_csv(r'C:\Users\aayus\OneDrive\Desktop\Aayu\College Project\OnlineRetail.csv', encoding='latin1')
tx_data['InvoiceDate'] = pd.to_datetime(tx_data['InvoiceDate'])
tx_data
tx_uk = tx_data.query("Country=='United Kingdom'").reset_index(drop=True)
tx_uk

到目前为止,一切都运行良好。但是只要添加这部分代码。它给出了一个错误。

#create 3m and 6m dataframes
tx_3m = tx_uk[(tx_uk.InvoiceDate < date(2011,6,1)) & (tx_uk.InvoiceDate >= date(2011,3,1))].reset_index(drop=True)
tx_6m = tx_uk[(tx_uk.InvoiceDate >= date(2011,6,1)) & (tx_uk.InvoiceDate < date(2011,12,1))].reset_index(drop=True)

错误是“dtype=datetime64[ns] 和日期之间的比较无效” 我还是 numpy 和 pandas 的新手,非常感谢您的帮助。

谢谢大家

【问题讨论】:

  • 根据错误消息,看起来tx_uk.InvoiceDate 是一个日期时间对象,您正试图将它与date 对象进行比较。
  • 改成tx_uk.InvoiceDate.dt.date &lt; date(2011,6,1)看看能不能用
  • @tidakdiinginkan 谢谢。你的解决方案奏效了。我也理解这个问题。

标签: python pandas numpy matplotlib python-datetime


【解决方案1】:

.dt.date 会将数据帧系列转换为datetime.date,,可以与date(2011,6,1) 进行比较

例如,tx_uk.InvoiceDate.dt.date &lt; date(2011,6,1) 会起作用!~

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2020-09-04
    • 2023-01-09
    • 2021-07-06
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多