【问题标题】:Convert Pandas Column to DateTime将 Pandas 列转换为 DateTime
【发布时间】:2015-01-02 00:11:02
【问题描述】:

我有一个以字符串格式导入的 pandas DataFrame 中的字段。 它应该是一个日期时间变量。 如何将其转换为日期时间列,然后根据日期进行过滤。

例子:

  • 数据帧名称:raw_data
  • 列名:Mycol
  • 价值 列中的格式:'05SEP2014:00:00:00.000'

【问题讨论】:

    标签: python datetime pandas


    【解决方案1】:

    使用to_datetime 函数,指定format 来匹配您的数据。

    raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
    

    【讨论】:

    • 注意:format 参数不是必需的。 to_datetime 很聪明。继续尝试,不要尝试匹配您的数据。
    • 为了避免SettingWithCopyWarning 使用@darth-behfans stackoverflow.com/a/42773096/4487805
    • 如果你只想要时间而不是日期怎么办?
    • 不是很聪明。即使某些列明确地采用 dayfirst=True 格式,对于同一列中的其他列,它仍将默认为 dayfirst=False。因此,使用显式格式规范或至少使用 dayfirst 参数更安全。
    • 省略格式字符串可能会导致此操作因大量记录而变慢。 This answer 讨论原因。如果您不包含格式字符串,看起来infer_datetime_format=True 也可以将解析速度提高到 ~5-10 倍(根据 pandas 文档)。
    【解决方案2】:

    如果您有多个要转换的列,您可以执行以下操作:

    df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)
    

    【讨论】:

    • 我需要执行以下操作来指定格式states_df[['from_datetime','to_datetime','timestamp']].apply(lambda _: pd.to_datetime(_,format='%Y-%m-%d %H:%M:%S.%f', errors='coerce'))
    【解决方案3】:

    您可以使用DataFrame方法.apply()对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
    

    【讨论】:

    • 谢谢!这很好,因为它更广泛适用,但另一个答案更直接。我很难决定我更喜欢哪个:)
    • 我更喜欢这个答案,因为它产生一个日期时间对象而不是 pandas.tslib.Timestamp 对象
    【解决方案4】:

    使用 pandas to_datetime 函数将列解析为 DateTime。此外,通过使用infer_datetime_format=True,它会自动检测格式并将提到的列转换为日期时间。

    import pandas as pd
    raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], infer_datetime_format=True)
    

    【讨论】:

    • 合并两张或多张床单可能会让人头疼,尤其是在涉及日期时间时。这个 infer_datetime_format 为我节省了很多时间。谢谢楼主!
    • 乐于帮助@Mike_Leigh !!此外,根据docs,在某些情况下,设置infer_datetime_format=True 可以将解析速度提高约5-10 倍。
    【解决方案5】:
    raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
    

    有效,但它会导致 Python 警告 试图在 DataFrame 中的切片副本上设置一个值。 尝试改用.loc[row_indexer,col_indexer] = value

    我猜这是由于一些链接索引造成的。

    【讨论】:

    • 我试了几次,但它有效:raw_data.loc[:,'Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b %Y:%H:%M:%S.%f')
    • 这对我有用: raw_data.loc[:,'Mycol'] = pd.to_datetime(raw_data.loc[:,'Mycol'], format='%d%b%Y:% H:%M:%S.%f')
    • df2.loc[:,'datetime'] = pd.to_datetime(df2['datetime']) /usr/lib/python3/dist-packages/pandas/core/indexing.py:543 : SettingWithCopyWarning: 试图在 DataFrame 中的切片副本上设置一个值。尝试改用 .loc[row_indexer,col_indexer] = value 查看文档中的警告:pandas.pydata.org/pandas-docs/stable/… self.obj[item] = s
    【解决方案6】:

    节省时间:

    raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'])
    

    【讨论】:

      【解决方案7】:

      请务必注意,pandas.to_datetime 几乎不会返回 datetime.datetime。来自the docs

      块引用

      Returns datetime
      If parsing succeeded. Return type depends on input:
      
      list-like: DatetimeIndex
      Series: Series of datetime64 dtype
      scalar: Timestamp
      
      In case when it is not possible to return designated types (e.g. when any element 
      of input is before Timestamp.min or after Timestamp.max) return will have 
      datetime.datetime type (or corresponding array/Series).
      

      块引用

      【讨论】:

      猜你喜欢
      • 1970-01-01
      相关资源
      最近更新 更多