LoginSignup
5
2

More than 1 year has passed since last update.

Pandasで複数列をまとめてdatetime型に変更する方法

Last updated at Posted at 2022-01-08

複数列をまとめてdatetime型に変更したい

日付データはdateime型にしておくと何かと便利
一つの列のみなら、pd.to_datetimeでかんたんに変換できるが、
複数列をまとめて処理したい場合の方法

使用データ

import pandas as pd

df = pd.read_csv('/sample.csv')

print(df)
>reg_date   start_date  end_date    id
>0  2007/05/20 18:47:28 2021/10/31 08:03:39 2021/11/07 08:03:39 AAA
>1  2007/05/20 19:30:51 2021/11/23 10:34:24 2021/11/23 10:36:12 BBB
>2  2007/05/20 22:54:15 2021/11/21 10:44:37 2021/11/21 10:45:23 CCC

df.dtypes
>reg_date           object
>start_date         object
>end_date           object

pd.to_datetime()での変換

pandas.to_datetime()関数を使うと、pandas.Seriesに対してdatetime64[ns]型に変換できる。

import pandas as pd
import datetime

pd.to_datetime(df['reg_date'])
>0         2007-05-20 18:47:28
>1         2007-05-20 19:30:51
>2         2007-05-20 22:54:15
>Name: reg_date, Length: 3, dtype: datetime64[ns]

複数列まとめてto_datetime()で変換

argにDataFrameを指定して利用する必要があり、
df['x'].to_datetime()という利用の仕方はできない

import pandas as pd
import datetime

df['reg_date'].to_datetime()
>AttributeError: 'Series' object has no attribute 'to_datetime'

当然複数列を対象としてもNG

import pandas as pd
import datetime

df.iloc[:,0:4].to_datetime()
>AttributeError: 'Series' object has no attribute 'to_datetime'

apply関数を利用することで複数列まとめて処理が可能

import pandas as pd
import datetime

df.iloc[:,0:4].apply(pd.to_datetime)
>   reg_date    start_date  end_date
>0  2007-05-20 18:47:28 2021-10-31 08:03:39 2021-11-07 08:03:39
>1  2007-05-20 19:30:51 2021-11-23 10:34:24 2021-11-23 10:36:12
>2  2007-05-20 22:54:15 2021-11-21 10:44:37 2021-11-21 10:45:23

df.iloc[:,0:4]apply(pd.to_datetime).dtypes
>reg_date      datetime64[ns]
>start_date    datetime64[ns]
>end_date      datetime64[ns]

以上

5
2
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
5
2