Get all columns with datetime type using pandas?

前端 未结 2 1164
情书的邮戳
情书的邮戳 2021-02-20 01:48

I have a huge DataFrame where the columns aren\'t ever in order nor do I know their name.

What do I do to find all the columns which are datetime types?

Most of

相关标签:
2条回答
  • 2021-02-20 02:12

    You can use pandas.DataFrame.select_dtypes(), and include only the datetime64 type.

    df.select_dtypes(include=['datetime64'])
    

    Demo

    >>> df
             dts1       dts2  ints
    0  2012-01-01 2004-01-01     0
    1  2012-01-02 2004-01-02     1
    2  2012-01-03 2004-01-03     2
    ..        ...        ...   ...
    97 2012-04-07 2004-04-07    97
    98 2012-04-08 2004-04-08    98
    99 2012-04-09 2004-04-09    99
    
    >>> df.select_dtypes(include=['datetime64'])
             dts1       dts2
    0  2012-01-01 2004-01-01
    1  2012-01-02 2004-01-02
    2  2012-01-03 2004-01-03
    ..        ...        ...
    97 2012-04-07 2004-04-07
    98 2012-04-08 2004-04-08
    99 2012-04-09 2004-04-09
    
    0 讨论(0)
  • 2021-02-20 02:27

    Since each column of a pandas DataFrame is a pandas Series simply iterate through list of column names and conditionally check for series.dtype of datetime (typically datetime64[ns]):

    for col in df.columns:
       if df[col].dtype == 'datetime64[ns]':
          print(col)
    

    Or as list comprehension:

    [col for col in df.columns if df[col].dtype == 'datetime64[ns]']
    

    Or as a series filter:

    df.dtypes[df.dtypes=='datetime64[ns]']
    
    0 讨论(0)
提交回复
热议问题