Python 顺便说一句,熊猫/Numpy datetime64和datetime64[ns]有什么区别

Python 顺便说一句,熊猫/Numpy datetime64和datetime64[ns]有什么区别,python,python-3.x,numpy,Python,Python 3.x,Numpy,熊猫/Numpydatetime64和datetime64[ns]之间有什么区别?另外,如何选择数据类型为datetime64[ns]的数据帧列 我尝试了以下方法: for col in df.columns: if (df[col].dtype == np.datetime64[ns]): #If column has dtype datetime64[ns] print(col) function(df[col]) ##apply a functio

熊猫/Numpydatetime64datetime64[ns]之间有什么区别?另外,如何选择数据类型为datetime64[ns]的数据帧列

我尝试了以下方法:

for col in df.columns:  
   if (df[col].dtype == np.datetime64[ns]): #If column has dtype datetime64[ns]  
       print(col)
       function(df[col]) ##apply a function to this column   
## RESULT: NameError: name 'ns' is not defined  
## If I try == np.datetime64, nothing gets printed.
我还尝试:

for col in df.columns: 
   if (df[col].dtype == 'datetime64[ns]'): 
       print(col)
       function(df[col])  
## RESULT: This works but it also print Columns with dtype object.
如何仅选择数据类型为datetime64[ns]的列?

使用select\u数据类型。 考虑这个DF

df = pd.DataFrame({'date1': pd.date_range(end = dt.datetime.today(), periods = 2), \
'date2': pd.date_range(end = dt.datetime.today(), periods = 2),\
'val1': np.arange(2),'bool': [True, False]})
df.dtypes

bool               bool
date1    datetime64[ns]
date2    datetime64[ns]
val1              int64
您可以使用选择类型来选择日期时间

df_new = df.select_dtypes(include = ['datetime'])
你得到

    date1                       date2
0   2017-12-05 11:02:05.580203  2017-12-05 11:02:05.580889
1   2017-12-06 11:02:05.580203  2017-12-06 11:02:05.580889

如果答案已经回答了你的问题,别忘了将其标记为已接受