Sandeepa Kariyawasam
Sandeepa Kariyawasam

Reputation: 577

Pandas Dataframe filter based on time

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?

Upvotes: 1

Views: 56

Answers (1)

jezrael
jezrael

Reputation: 862431

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)]

Upvotes: 1

Related Questions