将熊猫日期与Python日期进行比较的问题

时间:2020-08-26 09:12:33

标签: python pandas datetime

这是我编写的python代码,但找不到我做错的地方,希望有人可以在这里帮助我调试此代码 代码:

tx_data['InvoiceDate'] = pd.to_datetime(tx_data['InvoiceDate'])
tx_uk = tx_data.query("Country=='United Kingdom'").reset_index(drop=True)

#create 3month and 6month 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)

问题:

32 else:
33 typ = type(right).name
---> 34 raise TypeError(f"Invalid comparison between dtype={left.dtype} and {typ}")
35 return res_values

TypeError: Invalid comparison between dtype=datetime64[ns] and date

2 个答案:

答案 0 :(得分:0)

Python datetime类型和Numpy日期时间(由熊猫使用)不同。因此,您需要将datetime.datetime转换为numpy.datetime64才能解决此问题。

tx_3m = tx_uk[(tx_uk.InvoiceDate < numpy.datetime64("2011-6-1")) & (tx_uk.InvoiceDate >= numpy.datetime64("2011-3-1"))].reset_index(drop=True)
tx_6m = tx_uk[(tx_uk.InvoiceDate >= numpy.datetime64("2011-6-1")) & (tx_uk.InvoiceDate < numpy.datetime64("2011-12-1"))].reset_index(drop=True)

答案 1 :(得分:0)

尝试一下:

tx_data['InvoiceDate'] = pd.to_datetime(tx_data['InvoiceDate']).dt.date