Convert Pandas Column to DateTime

前端 未结 5 2082
情话喂你
情话喂你 2020-11-21 11:38

I have one field in a pandas DataFrame that was imported as string format. It should be a datetime variable. How do I convert it to a datetime column and then filter based

相关标签:
5条回答
  • 2020-11-21 11:42
    raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
    

    works, however it results in a Python warning of A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

    I would guess this is due to some chaining indexing.

    0 讨论(0)
  • 2020-11-21 11:46

    Use the pandas to_datetime function to parse the column as DateTime. Also, by using infer_datetime_format=True, it will automatically detect the format and convert the mentioned column to DateTime.

    import pandas as pd
    raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], infer_datetime_format=True)
    
    0 讨论(0)
  • 2020-11-21 11:48

    If you have more than one column to be converted you can do the following:

    df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)
    
    0 讨论(0)
  • 2020-11-21 11:54

    You can use the DataFrame method .apply() to operate on the values in Mycol:

    >>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
    >>> df
                        Mycol
    0  05SEP2014:00:00:00.000
    >>> import datetime as dt
    >>> df['Mycol'] = df['Mycol'].apply(lambda x: 
                                        dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
    >>> df
           Mycol
    0 2014-09-05
    
    0 讨论(0)
  • 2020-11-21 12:02

    Use the to_datetime function, specifying a format to match your data.

    raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
    
    0 讨论(0)
提交回复
热议问题