pandas中字串object 轉化 datetime 型別

網球小夥子發表於2020-11-19
import pandas as pd


from pandas import DataFrame
from dateutil.parser import parse

資料

data = DataFrame(columns=['date'], data=['2020-11-01','2020-11-05','2020-11-08','2020-11-11'])
data

在這裡插入圖片描述

data.info()

"""
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   date    4 non-null      object
dtypes: object(1)
memory usage: 160.0+ bytes"""

轉化

data['date'] = data['date'].apply(parse)

data.info()
"""
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   date    4 non-null      datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 160.0 bytes
"""

相關文章