0

I have the following code that results in the following dataframe:

date=['1/1/2016','2/2/2017','4/8/2017','3/3/2015']
distance=['10','20','30','40']
dd=list(zip(date,distance))
df=pd.DataFrame(dd,columns=['date','distance'])

   date           distance
0  1/1/2016       10
1  2/2/2017       20
2  4/8/2017       30
3  3/3/2015       40

I would like to select all data for the year 2017. If I try the following I get an empty dataframe because it does not include the month and day also:

df=df[df['date'].isin(['2017'])]

Is there a way to accomplish this without splitting the date list into month,day, and year? If I have to split the date how would I be able to keep the corresponding distance?

wanderweeer
  • 449
  • 1
  • 6
  • 16

2 Answers2

1
df['date'] = pd.to_datetime(df['date'])
df = df[df['date'].dt.year == 2017]
Yale Newman
  • 1,141
  • 1
  • 13
  • 22
0

If all you want is to filter '2017'. Then do it.

df[df.date.str.endswith('2017')
Mo. Atairu
  • 753
  • 8
  • 15