Guided Project (Heavy Traffic Indicators): Separating daytime from nighttime

Screen Link:
https://app.dataquest.io/c/95/m/524/guided-project%3A-finding-heavy-traffic-indicators-on-i-94/3/traffic-volume-day-vs-night

My Code:

day = traffic['date_time'][(traffic['date_time'].dt.hour >= 7) & (traffic['date_time'].dt.hour < 19)]
night = traffic['date_time'][(traffic['date_time'].dt.hour >= 19) & (traffic['date_time'].dt.hour < 7)]

Probably quite a simple question here – above is my original code for attempting to filter within the ‘date_time’ column to the correct rows for either daytime or nighttime, based on the criteria we were given. I seemed to get the correct number of rows for the daytime data…but not the nighttime data.

I’ve popped in the solution code below. Just to check my understanding, why is it necessary to copy the full dataframe BEFORE using series.dt.hour to filter to the correct rows in the dataset?

day = traffic.copy()[(traffic['date_time'].dt.hour >= 7) & (traffic['date_time'].dt.hour < 19)]
night = traffic.copy()[(traffic['date_time'].dt.hour >= 19) | (traffic['date_time'].dt.hour < 7)]```
1 Like

I would like to know the same thing… why is it necessary to make a copy of the dataframe before using series.dt.hour?

I used loc and it does the trick.

traffic_day = traffic.loc[(traffic[‘date_time’].dt.hour >= 7) & (traffic[‘date_time’].dt.hour < 19)]

traffic_night = traffic.loc[(traffic[‘date_time’].dt.hour >= 19) | (traffic[‘date_time’].dt.hour < 7)]