什么是差异btw Pandas / Numpy datetime64和datetime64 [ns]

时间:2017-12-06 18:57:23

标签: python python-3.x numpy

Pandas / Numpy datetime64 datetime64 [ns] 之间有什么区别?另外,如何选择dtype datetime64 [ns] 的Pandas DataFrame列?

我尝试了以下内容:

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.

如何只选择dtype datetime64 [ns]的列?

1 个答案:

答案 0 :(得分:0)

使用select_dtypes。 考虑一下这个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

您可以使用select_dtypes选择日期时间,

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