I have a where condition that includes a datetime column that needs to compare to a range of years. I’ve created a list of years and when the year in the datetime is >= to the year in the list, it needs to do something but I am getting an error: “Can only use .dt accessor with datetimelike values.” My datetime formate is: 2014-05-31 00:00:00
list_num = list(range(2012, 2010))
for year in list_num:
year_date = str(year)
for x in year_date:
df['ColF'] = np.where((df['ColA'] != 'N/A') & (df['ColDate'] != 'N/A') & df['ColDate'].dt.year >= x,(df['ColD']*2),0)
To create a pd.Series of years, use pd.date_range(start='1/1/2010', periods=3, freq="AS")
The range you specify is empty
The error message indicates that df["ColDate"] is not a datetime64[ns] type, and thus has no .dt methods or attributes. Use pd.to_datetime(df["ColDate"], errors='coerce'). Subsequently, "N/A" will be converted to pd.NaT instance, meaning you will have to use df["ColA"].notna() to weed it out.