2014-01-12 6 views
8

DataFrame을 Vincent 호환 형식으로 구문 분석하는 새로운 방법을 만들고 있습니다. 표준 Index이 필요합니다 (Vincent는 MultiIndex을 구문 분석 할 수 없습니다).데이터 프레임에 멀티 인덱스가 있는지 감지

팬더 DataFrameMultiIndex이 있는지 검색하는 방법이 있습니까?

In: type(frame) 
Out: pandas.core.index.MultiIndex 

나는 시도했다 : 나는 인용없이하려고하면

In: if type(result.index) is 'pandas.core.index.MultiIndex': 
     print True 
    else: 
     print False 
Out: False 

내가 얻을 : 어떤 도움을 주시면 감사

NameError: name 'pandas' is not defined 

.

(필자는 MultiIndex이 있으면, 그때 인덱스를 재설정 및 프리젠 테이션 단계에 대한 하나의 문자열 값으로 두 열을 병합하고 있습니다.)

+0

'이름 '팬더'을 먼저해야'수입 pandas'을 defined'하지 않습니다! – Winand

답변

13

당신은 객체가 클래스인지 여부를 확인하기 위해 isinstance을 사용할 수 있습니다 (또는 그 서브 클래스) :

if isinstance(result.index, pandas.core.index.MultiIndex): 
+0

저를 위해 일하십시오 - 이것은 나의 속기를 위해 "pd"로 팬더를 수입하는 습관이 있기 때문에 저에게 나의 과실을, 깨닫게했다. 이 편집 된 버전은 내 스크립트에서 작동했습니다. ifinstance (result.index, pd.core.index.MultiIndex) : –

0

어쩌면 가장 짧은 방법입니다 if type(result.index)==pd.MultiIndex:

2

또한

있다 609,343,210

있지만 isinstance 나 종류보다 훨씬 느립니다 :

timeit(len(result.index.names) > 1) 
The slowest run took 10.95 times longer than the fastest. This could mean that an intermediate result is being cached. 
1000000 loops, best of 3: 1.12 µs per loop 
In [254]: 

timeit(isinstance(result.index, pd.MultiIndex)) 
The slowest run took 30.53 times longer than the fastest. This could mean that an intermediate result is being cached. 
10000000 loops, best of 3: 177 ns per loop 
In [252]: 

) 
timeit(type(result.index) == pd.MultiIndex) 
The slowest run took 22.86 times longer than the fastest. This could mean that an intermediate result is being cached. 
1000000 loops, best of 3: 200 ns per loop 
+1

len (result.index.names)> 1은 초 단위이며 다른 숫자는 나노 초 단위이므로 실제 len은 1,120 ns입니다. –

+1

Arrgh! 감사합니다 @ 존슨, 그 성가신 친화적 인 단위 변환기 내 눈을 잡는 계속 (boost unittest 비슷한 일을). – danio

+0

MultiIndex에는 단 하나의 레벨 만있을 수 있습니까? – Konstantin

관련 문제