2017-10-13 4 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'を持つ2番目と4番目のカラムだけを返すにはどうすればよいですか?列の内容の型はまったく同じなので、select_dtypesは役に立ちません。 mapカラムを列で選択NAME dtype

答えて

2

使用type

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

関連する問題