In [1]: importpandasaspdIn [2]: importmatplotlib.pyplotasplt
Data used for this tutorial:
Air quality data
For this tutorial, air quality data about NO2 and Particulate
matter less than 2.5 micrometers is used, made available by
and downloaded using the
package.
The data set provides values
for the measurement stations , and in respectively Paris, Antwerp and London.
Initially, the values in datetime are character strings and do not
provide any datetime operations (e.g. extract the year, day of the
week,…). By applying the to_datetime function, pandas interprets the
strings and convert these to datetime (i.e. datetime64[ns,UTC])
objects. In pandas we call these datetime objects similar to
datetime.datetime from the standard library as pandas.Timestamp.
Why are these pandas.Timestamp objects useful? Let’s illustrate the added
value with some example cases.
What is the start and end date of the time series data set we are working
with?
In [9]: air_quality["datetime"].min(),air_quality["datetime"].max()Out[9]: (Timestamp('2019-05-07 01:00:00+0000', tz='UTC'), Timestamp('2019-06-21 00:00:00+0000', tz='UTC'))
Using pandas.Timestamp for datetimes enables us to calculate with date
information and make them comparable. Hence, we can use this to get the
length of our time series:
In [10]: air_quality["datetime"].max()-air_quality["datetime"].min()Out[10]: Timedelta('44 days 23:00:00')
The result is a pandas.Timedelta object, similar to datetime.timedelta
from the standard Python library and defining a time duration.
To user guide
The various time concepts supported by pandas are explained in the user guide section on time related concepts.
I want to add a new column to the DataFrame containing only the month of the measurement
In [11]: air_quality["month"]=air_quality["datetime"].dt.monthIn [12]: air_quality.head()Out[12]: city country datetime ... value unit month0 Paris FR 2019-06-21 00:00:00+00:00 ... 20.0 µg/m³ 61 Paris FR 2019-06-20 23:00:00+00:00 ... 21.8 µg/m³ 62 Paris FR 2019-06-20 22:00:00+00:00 ... 26.5 µg/m³ 63 Paris FR 2019-06-20 21:00:00+00:00 ... 24.9 µg/m³ 6
To user guide
An overview of the existing date properties is given in the
time and date components overview table. More details about the dt accessor
to return datetime like properties are explained in a dedicated section on the dt accessor.
What is the average NO2 concentration for each day of the week for each of the measurement locations?
In [13]: air_quality.groupby( ....: [air_quality["datetime"].dt.weekday,"location"])[
Plot the typical NO2 pattern during the day of our time series of all stations together. In other words, what is the average value for each hour of the day?
In [14]: fig,axs=plt.subplots(figsize=(12,4))In [15]:
Datetime as index
In the tutorial on reshaping,
pivot() was introduced to reshape the data table with each of the
measurements locations as a separate column:
In [18]: no_2=air_quality.pivot(index="datetime",columns="location",values="value")In [19]: no_2.head
Resample a time series to another frequency
Aggregate the current hourly time series values to the monthly maximum value in each of the stations.
In [22]: monthly_max=no_2.resample("ME").max()In [23]: monthly_maxOut[23]: location BETR801 FR04014 London Westminsterdatetime 2019-05-31 00:00:00+00:00 74.5 97.0 97.02019-06-30 00:00:00+00:00 52.5 84.7 52.0
A very powerful method on time series data with a datetime index, is the
ability to time series to another frequency (e.g.,
converting secondly data into 5-minutely data).
])
4 Paris FR 2019-06-20 20:00:00+00:00 ... 21.4 µg/m³ 6
[5 rows x 8 columns]
By using Timestamp objects for dates, a lot of time-related
properties are provided by pandas. For example the month, but also
year, quarter,… All of these properties are
accessible by the dt accessor.
"value"
]
.
mean
()
....:
Out[13]:
datetime location
0 BETR801 27.875000
FR04014 24.856250
London Westminster 23.969697
1 BETR801 22.214286
FR04014 30.999359
...
5 FR04014 25.266154
London Westminster 24.977612
6 BETR801 21.896552
FR04014 23.274306
London Westminster 24.859155
Name: value, Length: 21, dtype: float64
Remember the split-apply-combine pattern provided by groupby from the
tutorial on statistics calculation?
Here, we want to calculate a given statistic (e.g. mean NO2)
for each weekday and for each measurement location. To group on
weekdays, we use the datetime property weekday (with Monday=0 and
Sunday=6) of pandas Timestamp, which is also accessible by the
dt accessor. The grouping on both locations and weekdays can be done
to split the calculation of the mean on each of these combinations.
air_quality
.
groupby
(
air_quality
[
"datetime"
]
.
dt
.
hour
)[
"value"
]
.
mean
()
.
plot
(
....:
kind
=
'bar'
,
rot
=
0
,
ax
=
axs
....:
)
....:
Out[15]:
<Axes: xlabel='datetime'>
In [16]:
plt
.
xlabel
(
"Hour of the day"
);
# custom x label using Matplotlib
In [17]:
plt
.
ylabel
(
"$NO_2 (µg/m^3)$"
);
Similar to the previous case, we want to calculate a given statistic
(e.g. mean NO2) for each hour of the day and we can use the
split-apply-combine approach again. For this case, we use the datetime property hour
of pandas Timestamp, which is also accessible by the dt accessor.
()
Out[19]:
location BETR801 FR04014 London Westminster
datetime
2019-05-07 01:00:00+00:00 50.5 25.0 23.0
2019-05-07 02:00:00+00:00 45.0 27.7 19.0
2019-05-07 03:00:00+00:00 NaN 50.4 19.0
2019-05-07 04:00:00+00:00 NaN 61.9 16.0
2019-05-07 05:00:00+00:00 NaN 72.4 NaN
Working with a datetime index (i.e. DatetimeIndex) provides powerful
functionalities. For example, we do not need the dt accessor to get
the time series properties, but have these properties available on the
index directly: