- ๐PYTHON
9-2. ์๊ณ์ด ๋ฐ์ดํฐ ๋ค๋ฃจ๊ธฐ (dt)
shoo.
2023. 8. 13. 18:59
dt ํ์ฉํ๊ธฐ
3) ๋ฐ์ดํฐ ํ๋ ์์ ์ถ์ถํ ์(month)๋ง ์๋ ์ปฌ๋ผ์ ์ถ๊ฐํ๊ธฐ
In [11]: air_quality["month"] = air_quality["datetime"].dt.month
In [12]: air_quality.head()
Out[12]:
city country datetime ... value unit month
0 Paris FR 2019-06-21 00:00:00+00:00 ... 20.0 µg/m³ 6
1 Paris FR 2019-06-20 23:00:00+00:00 ... 21.8 µg/m³ 6
2 Paris FR 2019-06-20 22:00:00+00:00 ... 26.5 µg/m³ 6
3 Paris FR 2019-06-20 21:00:00+00:00 ... 24.9 µg/m³ 6
4 Paris FR 2019-06-20 20:00:00+00:00 ... 21.4 µg/m³ 6
[5 rows x 8 columns]
Timestamp ๊ฐ์ฒด๋ฅผ ๋ ์ง์ ์ฌ์ฉํ๋ฉด, Pandas์์ ๋ง์ ์๊ฐ ๊ด๋ จ ์์ฑ๋ค์ ์ ๊ณตํฉ๋๋ค.
์๋ฅผ ๋ค์ด, ์, ์ฐ๋, ๋ถ๊ธฐ ๋ฑ ์ด๋ฌํ ์์ฑ๋ค์ ๋ชจ๋ dt ๋ฅผ ํตํด ์ก์ธ์คํ ์ ์์ต๋๋ค.
4) ๊ฐ ์ธก์ ์์น์ ๋ํด์ ์์ผ๋ณ๋ก ํ๊ท ๋๋ ๊ตฌํ๊ธฐ
In [13]: air_quality.groupby(
....: [air_quality["datetime"].dt.weekday, "location"])["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
- weekday(์์์ผ=0, ์ผ์์ผ=6)
5) ํ๋ฃจ ๋์์ ์ ์ฒด ๊ธฐ์ ๊ด์ธก์์์ ์๊ฐ๋ณ ํ๊ท ๋๋ ํจํด์ ๊ทธ๋ฆฌ๊ธฐ
์ฆ, ํ๋ฃจ ์ค ๊ฐ ์๊ฐ๋ณ ํ๊ท ๊ฐ
In [14]: fig, axs = plt.subplots(figsize=(12, 4))
In [15]: air_quality.groupby(air_quality["datetime"].dt.hour)["value"].mean().plot(
....: kind='bar', rot=0, ax=axs
....: )
....:
Out[15]: <AxesSubplot: xlabel='datetime'>
In [16]: plt.xlabel("Hour of the day"); # custom x label using Matplotlib
In [17]: plt.ylabel("$NO_2 (µg/m^3)$");
- kind='bar' : ๋ง๋๊ทธ๋ํ
- rot=0 : x์ถ ๋ผ๋ฒจ์ ํ์ ๊ฐ๋๋ฅผ 0๋๋ก ์ค์ ํ์ฌ ๋ผ๋ฒจ์ด ์ํ์ผ๋ก ํ์๋๊ฒ ํฉ๋๋ค. ๊ธฐ๋ณธ๊ฐ์ 90๋๋ก ๋ผ๋ฒจ์ด ์์ง์ผ๋ก ํ์๋ฉ๋๋ค.
- ax=axs :๊ทธ๋ํ๋ฅผ ๊ทธ๋ฆด ๋ ์ฌ์ฉํ Axes ๊ฐ์ฒด๋ฅผ ์ง์ ํฉ๋๋ค. ๊ทธ๋ํ๋ฅผ ์๋ธํ๋กฏ์ ๊ทธ๋ฆด ๊ฒฝ์ฐ ax ๋งค๊ฐ๋ณ์๋ฅผ ์ฌ์ฉํด ํน์ ์๋ธํ๋กฏ ์์น๋ฅผ ์ ์ดํ ์ ์์ต๋๋ค. axs๋ ์ผ๋ฐ์ ์ผ๋ก matplotlib์์ ์๋ธํ๋กฏ์ ๋ฐฐ์ด์ ๋ํ๋ ๋๋ค.
๋ณธ ๋ด์ฉ์ ๊ณต๋ถ ๊ธฐ๋ก์ฉ์ผ๋ก ์ถ์ฒ๋ ํ๋ค์ค์ ๊ณต์๋ฌธ์(How to handle time series data with ease) ์ ๋๋ค