簡體   English   中英

熊貓:將數據框的列轉換為日期時間

[英]Pandas: convert column of dataframe to datetime

我有df

ID month
0       0001ee12f919a1b570658024bb59d118    2014-02 
1       0001ee12f919a1b570658024bb59d118    2014-03  
2       0001ee12f919a1b570658024bb59d118    2014-04  
3       0001ee12f919a1b570658024bb59d118    2014-05  
4       0001ee12f919a1b570658024bb59d118    2014-06  
5       0001ee12f919a1b570658024bb59d118    2014-07

我嘗試將year_month為日期時間。 我使用df1['month'] = pd.to_datetime(df1.month)但返回ValueError: Unknown string format如何解決?

您需要傳遞格式字符串'%Y-%m'因為to_datetime無法從您的字符串中推導出格式:

In [42]:
df['date'] = pd.to_datetime(df['month'], format='%Y-%m')
df

Out[42]:
                                 ID    month       date
0  0001ee12f919a1b570658024bb59d118  2014-02 2014-02-01
1  0001ee12f919a1b570658024bb59d118  2014-03 2014-03-01
2  0001ee12f919a1b570658024bb59d118  2014-04 2014-04-01
3  0001ee12f919a1b570658024bb59d118  2014-05 2014-05-01
4  0001ee12f919a1b570658024bb59d118  2014-06 2014-06-01
5  0001ee12f919a1b570658024bb59d118  2014-07 2014-07-01

In [43]:
df.info()           

<class 'pandas.core.frame.DataFrame'>
Int64Index: 6 entries, 0 to 5
Data columns (total 3 columns):
ID       6 non-null object
month    6 non-null object
date     6 non-null datetime64[ns]
dtypes: datetime64[ns](1), object(2)
memory usage: 192.0+ bytes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM