0

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.

0

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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] 

Comments

1

Corse date to datetime, extract year and check if equal to 2027

df[pd.to_datetime(df['Date']).dt.year==2027]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.