2017-09-25 5 views
1

Ich möchte Pandas DataFrames Typ überprüfen, d. H. Ich möchte angeben, welche Spaltenbeschriftungen ein DataFrame haben muss und welche Art von Datentyp (dtype) in ihnen gespeichert ist. Eine grobe Implementierung (diese question inspirierte) würde wie folgt funktionieren:Typ-Überprüfung Pandas DataFrames

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 

Ich habe nicht die Komplexität der Prüffunktion ausmacht, aber es fügt eine Menge von Standardcode.

@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) 

Gibt es eine pythonische Art der Überprüfung von Dataframes? Etwas, das eher wie the new Python 3.6 static type-checking aussieht?

Ist es möglich, es in Mypy zu implementieren?

Antwort

2

Vielleicht nicht der pythonic Weg, aber einen dict für Ihre Angaben unter Verwendung könnte den Trick (mit Schlüssel als Spaltennamen und Werten wie data types) tun:

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

Wenn Sie sie implementieren mit [OrderedDict] (https : //docs.python.org/2/library/collections.html#collections.OrderedDict) Sie können auch die Reihenfolge der Spalten überprüfen. – joachim

Verwandte Themen