Select rows by year

Viewed 4325

I want to select rows by a year:

import pandas as pd
import numpy as np

df = pd.DataFrame(columns=['Start','End'],data=[[np.datetime64('2001-01-01'),np.datetime64('2001-07-01')],[np.datetime64('2002-01-01'),np.datetime64('2002-11-01')]])
print(df)

       Start        End
0 2001-01-01 2001-07-01
1 2002-01-01 2002-11-01

So i try:

df_2001 = df.loc[df['Start'.year == 2001)]]
Traceback (most recent call last):
  Python Shell, prompt 16, line 1
invalid syntax: <string>, line 1, pos 30

How can i select by year in a datetime64 column?

1 Answers

Use dt.year:

df_2001 = df[df['Start'].dt.year == 2001]
Related