2017-09-25 6 views
1

팬더 데이터 프레임을 입력 확인하고 싶습니다. 즉, DataFrame에 있어야 할 열 레이블과 어떤 종류의 데이터 유형 (dtype)이 저장되어 있는지 지정하고 싶습니다.유형 검사 팬더 데이터 프레임

from collections import namedtuple 
Col = namedtuple('Col', 'label, type') 

def dataframe_check(*specification): 
    def check_accepts(f): 
     assert len(specification) <= f.__code__.co_argcount 
     def new_f(*args, **kwds): 
      for (df, specs) in zip(args, specification): 
       spec_columns = [spec.label for spec in specs] 
       assert (df.columns == spec_columns).all(), \ 
        'Columns dont match specs {}'.format(spec_columns) 

       spec_dtypes = [spec.type for spec in specs] 
       assert (df.dtypes == spec_dtypes).all(), \ 
        'Dtypes dont match specs {}'.format(spec_dtypes) 
      return f(*args, **kwds) 
     new_f.__name__ = f.__name__ 
     return new_f 
    return check_accepts 

나는 검사 기능의 복잡성을 꺼리지 않는다하지만 상용구 코드를 많이 추가합니다 (이 question에서 영감을)은 원유 구현은 다음과 같이 작동합니다.

@dataframe_check([Col('a', int), Col('b', int)], # df1 
       [Col('a', int), Col('b', float)],) # df2 
def f(df1, df2): 
    return df1 + df2 

f(df, df) 

더 많은 데이터 검사 유형의 유형 체크가 있습니까? the new Python 3.6 static type-checking과 비슷한 모양인가요?

mypy에서 구현할 수 있습니까? 아마도

답변

2

아니라 대부분의 파이썬 방법이 있지만, (data types 같은 열 이름과 같은 키와 값) 트릭 할 수 귀하의 사양에 대한 딕셔너리를 사용 : 당신이 HTTPS ([OrderedDict] 그것을 구현하는 경우

import pandas as pd 

df = pd.DataFrame(columns=['col1', 'col2']) 
df['col1'] = df['col1'].astype('int') 
df['col2'] = df['col2'].astype('str') 

cols_dtypes_req = {'col1':'int', 'col2':'object'} #'str' dtype is 'object' in pandas 

def check_df(dataframe, specs): 
    for colname in specs: 
     if colname not in dataframe: 
      return 'Column missing.' 
     elif dataframe[colname].dtype != specs[colname]: 
      return 'Data type incorrect.' 
    for dfcol in dataframe: 
     if dfcol not in specs: 
      return 'Unexpected dataframe column.' 
    return 'Dataframe meets specifications.' 

print(check_df(df, cols_dtypes_req)) 
+2

을 : //docs.python.org/2/library/collections.html#collections.OrderedDict) 열의 순서를 확인할 수도 있습니다. – joachim