Specifying date format when converting with pandas.to_datetime

前端 未结 2 1483
南方客
南方客 2020-12-01 15:48

I have data in a csv file with dates stored as strings in a standard UK format - %d/%m/%Y - meaning they look like:

12/01/2012
30/01/2012
         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 16:25

    You can use the parse_dates option from read_csv to do the conversion directly while reading you data.
    The trick here is to use dayfirst=True to indicate your dates start with the day and not with the month. See here for more information: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers.read_csv.html

    When your dates have to be the index:

    >>> import pandas as pd
    >>> from StringIO import StringIO
    >>> s = StringIO("""date,value
    ... 12/01/2012,1
    ... 12/01/2012,2
    ... 30/01/2012,3""")
    >>> 
    >>> pd.read_csv(s, index_col=0, parse_dates=True, dayfirst=True)
                value
    date             
    2012-01-12      1
    2012-01-12      2
    2012-01-30      3
    

    Or when your dates are just in a certain column:

    >>> s = StringIO("""date
    ... 12/01/2012
    ... 12/01/2012
    ... 30/01/2012""")
    >>> 
    >>> pd.read_csv(s, parse_dates=[0], dayfirst=True)
                     date
    0 2012-01-12 00:00:00
    1 2012-01-12 00:00:00
    2 2012-01-30 00:00:00
    

提交回复
热议问题