Invalid comparison between dtype=datetime64[ns] and date

Viewed 10498

I'm trying to work around this issue that I am facing here.

#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

Everything is working perfectly till here. But as soon as add this section of the code. It gives an error.

#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)

The error is "Invalid comparison between dtype=datetime64[ns] and date" I am still new to numpy and pandas, so would really appreciate the help.

Thanks you guys

1 Answers

.dt.date will convert the dataframe series to datetime.date, which can be compared to date(2011,6,1)

e.g., tx_uk.InvoiceDate.dt.date < date(2011,6,1) will work!~

Related