2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【python】日付を分割

Last updated at Posted at 2020-03-29

時系列データを分析する際、タイムスタンプなどのカラムで
「2016-12-17 09:59:17」
というような形式で保存されている場合があります。
この形式から、機械学習で扱えるように、
日付を年、月、日、時間、曜日に分割する方法を掲載します。

今回は、下記のようなダミーデータを使用します。

time.py
import pandas as pd
df = pd.read_csv('df.csv')
df.head()

# 出力
    patient	Last UpDdated
0	5.0	    2020-03-22 10:00:00
1	4.0	    2020-03-22 11:00:00
2	6.0	    2020-03-22 12:00:00
3	10.0	2020-03-23 10:00:00
4	3.0	    2020-03-23 11:00:00

df.info()
#出力
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 21 entries, 0 to 20
Data columns (total 3 columns):
patient          21 non-null float64
Last UpDdated    21 non-null object
dtypes: float64(2), object(1)
memory usage: 800.0+ bytes

Last UpDated列の日付を分割します。
■順番
①object型からdatetime64[ns]型に変換
  pd.to_datetime(df['Last UpDdated'])
②.dt.〜で年、月、日、時間、曜日、を取得
  df['Last UpDdated'].dt.month

time.py
df['Last UpDdated'] = pd.to_datetime(df['Last UpDdated']) # 型を変換
df.dtypes

# 出力
patient                 float64
Last UpDdated    datetime64[ns]
dtype: object

# 列「manth」追加
df['month'] = df['Last UpDdated'].dt.month
# 列「day」追加
df['day'] = df['Last UpDdated'].dt.day
# 列「hour」追加
df['hour'] = df['Last UpDdated'].dt.hour
# 列「week」追加
df['week'] = df['Last UpDdated'].dt.dayofweek
# Last UpDdatedを削除
df = df.drop(['Last UpDdated'],axis=1)

df.head()

#出力
	patient	month  day	hour  week
0	5.0	    3	   22	10	  6
1	4.0	    3	   22	11	  6
2	6.0	    3	   22	12	  6
3	10.0	3	   23	10	  0
4	3.0	    3	   23	11	  0

Last UpDated列の値を元に、月、日、時間、曜日列が追加されました!
曜日は0〜6のint型になっています。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?