Get all columns with datetime type using pandas?

I have a huge DataFrame where the columns are out of order and I don't know their name.

What do I need to find all columns of datetime type?

Most decisions are online, the poster knows the name of the column, so I have a small problem, just like me. What can I do in this situation?

+5
source share
2 answers

You can use pandas.DataFrame.select_dtypes() and include only 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 
+7
source

Since each pandas DataFrame column is a pandas series, just iterate over the list of column names and conditionally check for series.dtype datetime (usually datetime64 [ns]):

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

Or as a 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
source

Source: https://habr.com/ru/post/1264405/


All Articles