2017-10-13 3 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가 도움이되지 않습니다. 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

관련 문제