I have a dataset that has datetime values in it. I would like to remove all rows within a specific column that contain a certain year. All rows that contain 2027 should be removed.
Data
ID Date Type
AA 2027-04-03 00:00:00 ok
AA 2027-05-06 00:00:00 no
BB 2027-07-05 00:00:00 yes
BB 2026-06-05 00:00:00 yes
Desired
ID Date Type
BB 2026-06-05 00:00:00 yes
Doing
df1 = df[df["Date"].str.contains("-2027") == False]
Any suggestion is appreciated. Error: AttributeError: Can only use .str accessor with string values!
I believe I need to do some type of conversion here.
CodePudding user response:
since the data is already a datetime type, str accessor fails. Following should resolve it
df1=df[df["Date"].dt.year != 2027]
ID Date Type
3 BB 2026-06-05 yes
CodePudding user response:
You can convert the column date to a string and apply your code:
df['Date'] = df['Date'].astype(str)
df1 = df[df["Date"].str.contains("2027") == False]
CodePudding user response:
Corse date to datetime, extract year and check if equal to 2027
df[pd.to_datetime(df['Date']).dt.year==2027]