【问题标题】:Pandas: convert column of dataframe to datetime熊猫:将数据框的列转换为日期时间
【发布时间】:2016-08-18 11:07:43
【问题描述】:

我有 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 我该如何解决?

【问题讨论】:

    标签: python datetime pandas


    【解决方案1】:

    您需要传递格式字符串'%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
    

    【讨论】:

    • 我有一个问题,这个字符串ValueError: time data '\\N' does match format specified
    • 那么您有 duff 数据,您可以通过执行以下操作强制转换:df['date'] = pd.to_datetime(df['month'], format='%Y-%m', errors='coerce') 将错误值强制为NaT
    • 我怎样才能把它变成这种形式:YYYY-MM
    • @jezrael,你能说一下,我如何将YYYY-MM-DD 转换为YYYY-MM?我尝试df1['date'] = [w[:6] for w in df1['date']] 但它返回给我TypeError: 'Timestamp' object has no attribute '__getitem__'
    • 你为什么要这个?在这里你会得到一个datetime dtype,如果不将其转换为字符串,你就无法在显示的输出中获得该格式,如果你这样做,它与你开始使用的没有什么不同
    猜你喜欢
    • 2019-05-22
    • 2020-03-14
    • 2018-12-08
    • 2019-01-24
    • 1970-01-01
    • 2017-08-24
    • 2015-03-25
    相关资源
    最近更新 更多