LoginSignup
56
50

More than 3 years have passed since last update.

pandasのindexはdatetimeにすると便利

Last updated at Posted at 2019-06-23

はじめに

時系列を含むデータをpandasで処理する場合、indexにdatetime型を指定すると便利だったので、
備忘録的にまとめます。

使用データ

ネット上で拾ってきた2010年から2019年までの時系列データを使用します。

df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date")
df.head()
date A B
2010-04-01 93.74 1859.96
2010-04-02 94.61 1859.96
2010-04-05 94.28 1836.82
2010-04-06 93.64 1839.07
2010-04-07 93.21 1800.12

ここが便利

1. 日付を指定することで、データを選択できる。

indexにdatetime型の方式で日付を指定すると、指定範囲のデータを取得できる。

年の指定

df["2011"].head(2)
date A B
2011-01-03 81.67 1663.29
2011-01-04 82.06 1659.39

月の指定

df["2011-3"].head(2)
date A B
2011-03-01 81.92 1424.76
2011-03-02 81.84 1374.43

2.範囲指定もできる。

スライスによる範囲指定もできる

df["2012-04":"2012-05"]
date A B
2012-04-02 81.64 1654.39
〜〜 〜〜
2012-05-31 78.36 1471.49

3.特定の月(日)だけ抜き出す

8月だけ抜き出すというような処理も可能です。

df[df.index.month == 8]
date A B
2010-08-02 86.53 1509.63
2010-08-03 85.88 1527.62
〜〜 〜〜
2018-08-30 110.98 2840.16
2018-08-31 111.04 2840.16

4.年月日ごとに計算を行う。

# 年なら'y'、日なら'D'を指定してください。
# もちろんmeanを他の計算メソッドに当てても計算できます。
df.resample('M').mean()
date A B
2010-04-30 93.455909 1784.934091
2010-05-31 91.914762 1684.609048
〜〜 〜〜

参考サイト様

https://note.nkmk.me/python-pandas-rolling/
https://towardsdatascience.com/basic-time-series-manipulation-with-pandas-4432afee64ea

56
50
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
56
50