In this assignment we study cycling in Paris, using the hourly counts of one of the bike counters that the city has installed in its streets.
This is a first contact with time series in pandas; we will practice
parsing strings into timestamps, and dealing with time zones
the
.dtaccessor, to extract the hour, the day of the week, etc.slicing a dataframe on its time index
resample(), to aggregate by day, week, monthand finally joining with another time series, daily weather data
the companion assignment time series: events deals with series that are not on a regular grid
here is the kind of pictures we will end up with
import pandas as pd
import matplotlib.pyplot as plt
print(f"using pandas {pd.__version__}")
# time series look better in a wide figure
plt.rcParams["figure.figsize"] = (10, 4)using pandas 3.0.6
# optional
import itables
itables.init_notebook_mode()0. the data¶
there are two files in the data/ folder
| file | one row per | columns |
|---|---|---|
bike-counter.csv | hour | timestamp, count (number of bikes that went through the counter) |
weather.csv | day | jour, temperature (°C, daily mean), rain_mm (daily total) |
the counter is on the voie Georges Pompidou, along the Seine; it counts the bikes going in one direction only
we start with the first one
1. parsing the timestamps¶
loading¶
load
data/bike-counter.csvinto a dataframe nameddflook at the first rows and at the types of the columns - what is the type of the
timestampcolumn ?the name
countis unfortunate, becausedf.countis a method of the dataframe;
rename that column inton_bikes
# your codeconverting¶
we want to turn the timestamp column into actual timestamps
use
pd.to_datetime()for that; what do you get ? read the message carefullylook at the strings in the data: apart from the date and the hour, what else is there ?
how many different values are there for that part ? can you guess why ?
# your codehint
the last 6 characters of a string can be obtained with df.timestamp.str[-6:]
and then you can use value_counts()
converting, again¶
pandas has a hard time with a column that mixes several time zone offsets
the way out is to ask for everything to be expressed in UTC, using the utc=True option
redo the conversion with that option, and store the result back into the
timestampcolumn;
what is the dtype now ?we are interested in the local time in Paris, since this is when people go to work
convert that column to the timezone"Europe/Paris"
you will need to find the right method in the.dtaccessor (or do a search ontz_convert)
# your code2. the .dt accessor¶
now that timestamp has a proper type, the .dt accessor gives us access to all the details
add these columns to df
| column | content |
|---|---|
hour | the hour of the day, 0 to 23 |
weekday | the day of the week, as a string like "Monday" |
is_weekend | a boolean, True on Saturday and Sunday |
month | the month, as a number 1 to 12 |
# your codehint
.dt.hour,.dt.monthare attributes.dt.day_name()is a method, and there is also an attribute.dt.dayofweekthat returns a number with 0 for Monday
the hourly profile¶
what is the average number of bikes per hour of the day ? use a
groupbyand plot the result with.plot()
what are the busiest hours ? does that match your expectations ?now do the same but separately for week days and for week ends, so that both curves show on the same plot
we expect something like the picture in the introduction
hint
for the second question, group by 2 criteria, and think about unstack() to get 2 columns
this is the same trick as what we have seen with pivot_table
# your code3. using the time as the index¶
it is very common to use the timestamps as the index of a time series; this makes slicing very convenient
make
timestampthe index ofdfmake sure the index is sorted in chronological order (check that with
index.is_monotonic_increasing)what are the first and the last timestamps ? so, how long is the period covered ?
# your codemissing data¶
this is a counter that sits in the street, so there can be some missing data
we expect one row per hour
how many rows would you expect between the first and the last timestamp ? how many do we have ?
how many rows contain
NaNin then_bikescolumn ?which days are entirely missing ?
hint
pd.date_range()can create the index with all the hours; use the optionfreq="h"or use
df.asfreq("h"), that creates the missing rows withNaNin it
# your code4. slicing¶
now that we have a time index, we can slice with .loc[] using strings that look like dates
let us practice, using df.loc[...] to answer these questions
what are the total number of bikes counted in December 2025 ?
how many rows do we have between January 1st and January 7th 2026 (both included) ?
is the end of the slice included or not ?how many bikes in total in the morning rush, i.e. between 7:00 and 10:00 (all days included) ?
how many rows do we have on 2026-03-29 ? and on 2025-10-26 ? why is that ?
hint
for question 3, you can build a mask from the hour of the day, which is available
as an attribute of the index (df.index.hour) or from the column we have created earlier
and if you like, there is also a method between_time() that does it directly
# your codeis the practice growing ? (optional)¶
our data covers the period from September 12th to October 11th twice: in 2025 and in 2026
compare the total number of bikes in each of these 2 periods
# your code5. resampling¶
resample() is like a groupby, where the groups are time intervals; it is the tool of choice to change the granularity of a time series
so, to move from one point per hour to one point per day
compute
daily, the total number of bikes per day (aSeries), and plot itwhat is the busiest day ? and the least busy one ?
hint:idxmax()andidxmin()
# your codebeware of the missing data¶
some days have no bike at all, which is suspicious - recall that some days were missing entirely
on the plot above they show as a few sharp drops down to 0, in the late summer and in the fall
which are these days ? what happened ? what does
sum()return on a group with no data at all ?fix
dailyso that these days show up asNaNrather than 0
hint: look at the options ofsum()plot again, but only the last 2 months, and with
marker="."to see the individual points;
what doesplot()do with aNaN?
# your codeweekly and monthly¶
compute and plot the number of bikes per week, and per month
in the resulting series, what is the first date for a month ? and for a week ?the first and last months are not complete; in addition, the months have different lengths
so a monthly total is not the best way to compare them; compute the average per day instead
hint: you can usedailymake a dataframe with 3 columns
total,meanandmaxgiving, for each month, the corresponding aggregates of the daily numbers
hint:agg()
# your codehint
the aliases for the frequency are "W" for weeks, and "ME" for the end of the months
("MS" for the start of the months); in older versions of pandas it was "M"
6. adding the weather¶
does the weather make a difference ? let us find out with the second file
load
data/weather.csvinto a dataframeweather, and make sure the columnjourbecomes a proper timestamp
careful with the format:12/09/2025is meant to be September 12th; what would happen if pandas chose to read it as December 9th ?
use theformat=option ofpd.to_datetimeto say what you meanmake that column the index of
weathercombine
dailyandweatherinto one dataframeboth, with the 3 columnsn_bikes,temperatureandrain_mm
at that point you may run into an issue with the indexes - that is because one has a time zone, and the other one has not
we recommend to remove the time zone fromdaily, you can usetz_localize(None)on its index
# your codea look at the result¶
are there less bikes on rainy days ?
let us say a day is rainy if there is more than 1mm of rain
compare the average number of bikes on rainy days and on other daysdraw a scatter plot of the number of bikes against the temperature, using
df.plot.scatter()or similarwhat is the correlation between the 3 columns ?
hint:corr()
# your codeappendix: where the data comes from¶
the bike counts come from the open data portal of the city of Paris, dataset comptage vélo - données compteurs
https://opendata .paris .fr the weather comes from the Open-Meteo archive API, for Paris
https://open -meteo .com the script
fetch-data.py, that comes with this assignment, was used to acquire this datait picks one counter, and exports the hours in local time with the UTC offset, as the original does
and it writes the days of the weather in the French format on purpose
the data is frozen, no need to refresh it