LoginSignup
0
0

More than 5 years have passed since last update.

pandasの時刻情報の変換

Last updated at Posted at 2017-02-19

pandas.DataFrameにはいっている文字列形式時刻情報をdatetime形式に変換します。

まず、時刻情報が入ったDataFrameがあるとして、

print (df["時刻"])
0          2016年1月1日1時
1          2016年1月1日2時
2          2016年1月1日3時
3          2016年1月1日4時
4          2016年1月1日5時
5          2016年1月1日6時
6          2016年1月1日7時
7          2016年1月1日8時
8          2016年1月1日9時
9         2016年1月1日10時
10        2016年1月1日11時
11        2016年1月1日12時
12        2016年1月1日13時
13        2016年1月1日14時
14        2016年1月1日15時
15        2016年1月1日16時
16        2016年1月1日17時
17        2016年1月1日18時
18        2016年1月1日19時
19        2016年1月1日20時
20        2016年1月1日21時
21        2016年1月1日22時
22        2016年1月1日23時
23        2016年1月1日24時

のようになっているとします。因みに上の時刻情報は0時の代わりに24時になっています。これを、以下ような関数convを定義して、DataFrame.apply()に投げます。1-24時の範囲は変換時にエラーになるので、conv()内で0-23時に変換しています。

def conv(line):
    import re
    lst = re.split("[年月日時]",line)[:-1]
    lst[-1] = str(int(lst[-1]) - 1)
    return datetime.datetime.strptime("-".join(lst), "%Y-%m-%d-%H")
df["時刻"] = df["時刻"].apply(conv)
print(df["時刻"])
0      2016-01-01 00:00:00
1      2016-01-01 01:00:00
2      2016-01-01 02:00:00
3      2016-01-01 03:00:00
4      2016-01-01 04:00:00
5      2016-01-01 05:00:00
6      2016-01-01 06:00:00
7      2016-01-01 07:00:00
8      2016-01-01 08:00:00
9      2016-01-01 09:00:00
10     2016-01-01 10:00:00
11     2016-01-01 11:00:00
12     2016-01-01 12:00:00
13     2016-01-01 13:00:00
14     2016-01-01 14:00:00
15     2016-01-01 15:00:00
16     2016-01-01 16:00:00
17     2016-01-01 17:00:00
18     2016-01-01 18:00:00
19     2016-01-01 19:00:00
20     2016-01-01 20:00:00
21     2016-01-01 21:00:00
22     2016-01-01 22:00:00
23     2016-01-01 23:00:00

datetimeの形式になりました。

0
0
0

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
0
0