Pandas/Numpy datetime64和datetime64ns有什么区别?另外,如何选择带有dtype datetime64ns的Pandas datetime64ns列?
我尝试了以下几点:
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 datetime64ns的列?
发布于 2017-12-06 19:03:17
使用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.580889https://stackoverflow.com/questions/47681578
复制相似问题