Home > Back-end >  Pandas Dataframe filter based on time
Pandas Dataframe filter based on time

Time:10-12

From the datetime object in the dataframe I created two new columns based on month and day.

data["time"] = pd.to_datetime(data["datetime"])
data['month']= data['time'].apply(lambda x: x.month)
data['day']= data['time'].apply(lambda x: x.day)

The resultant data had the correct month and day added to the specific columns.

Then I tried to filter it based on specific day

data = data[data['month']=='9']
data = data[data['day']=='2']

This values were visible in the dataframe before filtering.

This returns an empty dataframe. What did I do wrong?

CodePudding user response:

Compare by 9,2 like integers, without '':

data = data[(data['month']==9) & (data['day']==2)]

Or:

data = data[(data['time'].dt.month == 9) & (data['time'].dt.day == 2)]
  • Related