【问题标题】:pandas convert a column to datetime but its type is not datetime熊猫将列转换为日期时间,但其类型不是日期时间
【发布时间】:2019-04-16 23:59:19
【问题描述】:

我需要将数据框 colmun 转换为 pandas 中的日期时间。 但是,它的数据类型不是我所期望的。

>>> df = pd.DataFrame(['2009-11-27'], columns = ['my_col'])
>>> df.dtypes['my_col']
dtype('O')
>>> pd.to_datetime(df['my_col'], format='%Y-%m-%d',  errors = 'coerce')
 0   2009-11-27
 Name: my_col, dtype: datetime64[ns]
>>> df.dtypes['my_col']
dtype('O')
>>> df['my_col'] = pd.to_datetime(df['my_col'], format='%Y-%m-%d',  errors = 'coerce')
>>> df.dtypes['my_col']
dtype('<M8[ns]')
 >>> df['my_col'] = pd.to_datetime(df['my_col'], format='%Y-%m-%d',  errors = 'coerce')
  >>> df.dtypes['my_col']
  dtype('<M8[ns]')
  >>> df = pd.DataFrame(['2009-11-27'], columns = ['my_col'])
  >>> df['my_col'] = pd.to_datetime(df['my_col'], format='%Y-%m-%d',  errors = 'coerce')
  >>> df.dtypes['my_col']
 dtype('<M8[ns]')

我需要获取列的数据类型,以便我的代码可以做

 if df.dtypes['my_col'] in (np.datetime64, datetime.datetime):
      do something .....

有什么建议吗?

【问题讨论】:

    标签: python python-3.x pandas datetime dataframe


    【解决方案1】:

    直接查询列的dtype属性,可以这样做

    df['my_col'].dtype
    # dtype('<M8[ns]')
    
    np.issubdtype(df['my_col'].dtype, np.datetime64)
    # True
    

    【讨论】:

    • 谢谢,如果我有很多列,如何在一个“np.issubdtype()”表达式中同时检查所有列的类型?
    • 如果满足条件,@user3448011 df[['a' 'b', 'c', ...]].dtypes.map(lambda x: np.issubdtype(x, np.datetime64)).all() 应该返回 True。但是,如果您选择列,也许您可​​能只想要df.select_dtypes(include=[np.datetime64])
    • 我有很多列:int、float、string、datetime,我需要根据它的数据类型做不同的事情。例如对于所有日期时间列,我会做一些事情。对于所有 int 列,我会做另一件事。
    • @user3448011 好的,还有什么我可以为你做的吗?
    【解决方案2】:

    使用系列与dtypes

    df.iloc[0,:].dtypes
    dtype('<M8[ns]')
    

    或者

    df.select_dtypes(include=[np.datetime64, 'datetime' ,'datetime64'])
    

    有了select_dtypes,你的代码就可以了

    df1=df.select_dtypes(include=[np.datetime64, 'datetime' ,'datetime64'])
    do something
    df2=df.drop(df1.columns,1)
    do somthing
    

    【讨论】:

      【解决方案3】:

      pd.to_datetime 不在位。您基本上拥有它 - 只需在转换日期时间后重新分配列。

      >>> import pandas as pd
      >>> df = pd.DataFrame(['2009-11-27'], columns = ['my_col'])
      >>> df.dtypes['my_col']
      dtype('O')
      >>> df.my_col = pd.to_datetime(df['my_col'], format='%Y-%m-%d',  errors = 'coerce')
      >>> df.dtypes['my_col']
      dtype('<M8[ns]')
      

      您可以使用它来检查列是否为特定类型 - pandas dtypes 实际上只是 numpy dtypes。

      >>> type(df.my_col.dtype)
      <class 'numpy.dtype'>
      

      你可以找到the list of numpy dtypes here.

      这意味着你可以像这样进行比较 -

      >>> import numpy as np
      >>> df.dtypes['my_col'] == np.dtype('<M8[ns]')
      True
      >>> df.dtypes['my_col'] == np.dtype('<M8[ms]')
      False
      >>> df.dtypes['my_col'] in [np.dtype('<M8[ns]'), np.dtype('<M8[ms]')]
      True
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-08
        • 1970-01-01
        • 2017-08-24
        • 2018-06-18
        • 2017-05-20
        • 1970-01-01
        相关资源
        最近更新 更多