2017-10-13 64 views
1
import pandas as pd 
import numpy as np 
cols = ['string',pd.Timestamp('2017-10-13'), 'anotherstring', pd.Timestamp('2017-10-14')] 
pd.DataFrame(np.random.rand(5,4), columns=cols) 

如何才能找回第二和第四列(其中有dtype'date time.datetime')?列內容的類型完全相同,所以select_dtypes不起作用。按列NAME選擇列dtype

回答

2

使用typemap

df = df.loc[:, df.columns.map(type) == pd.Timestamp] 
print (df) 
    2017-10-13 00:00:00 2017-10-14 00:00:00 
0    0.894932    0.502015 
1    0.080334    0.155712 
2    0.600152    0.206344 
3    0.008913    0.919534 
4    0.280229    0.951434 

詳情:

print (df.columns.map(type)) 
Index([       <class 'str'>, 
     <class 'pandas._libs.tslib.Timestamp'>, 
           <class 'str'>, 
     <class 'pandas._libs.tslib.Timestamp'>] 

print (df.columns.map(type) == pd.Timestamp) 
[False True False True] 

替代解決方案:

df1 = df.loc[:, [isinstance(i, pd.Timestamp) for i in df.columns]] 
print (df1) 
    2017-10-13 00:00:00 2017-10-14 00:00:00 
0    0.818283    0.128299 
1    0.570288    0.458400 
2    0.857426    0.395963 
3    0.595765    0.306861 
4    0.196899    0.438231 
+0

感謝。我有datetime.datetime,所以把它與頂部的一個簡單的'導入日期時間'結合起來,我就完成了。 – ac24

+0

是的,確切地說。不用謝! – jezrael