jeudi 30 juin 2016

Decorator to pass pandas Series into one-column DataFrames

I want to write a decorator that I can use on functions that are written for Pandas DataFrame, so that when they receive an input that is actually a Series (or maybe even an array) it first transforms that input into a one-column Pandas DataFrame out of generality. That way I can make every function work for both DataFrames and series writing functions only for DataFrames.

Something like

@wraps
def does_smt(df, **kwargs):
    for c in df.columns:
        df[c] = do_something(df[c], df.index)
    return df

does_smt(series) # and it also works

I'm not too good with python decorators yet, but judging by Pint's ureg.wraps decorator I'm thinking it can be done. I checked that decorator but, then again, since I'm having trouble understanding decorators, I couldn't figure out how to adapt that. I also searched for a decorator like that already defined in Pandas but there seems to be none.

First question: How can I do that?

Second: Is that recommended, or is there a better way?

Cheers

Aucun commentaire:

Enregistrer un commentaire