I have a Pandas dataframe and want to do different things with it. Now my function has this structure:
def process_dataframe(df, save_to_file, print_to_screen, etc):
...
if save_to_file:
df.to_csv(filename)
elif print_to_screen:
print df
elif...
Which is an ugly if else case. I want to use a functional instead. A function pointer. Something like this. I create several functions:
def save_to_file(df, filename):
return create_function(to_csv, filename???)
def print_to_screen(df):
return create_function(print)
Which means I can change the structure of my function to this single line instead:
result = process_dataframe(save_to_file)
...
...
def process_dataframe(df, my_functional):
return my_functional(df)
The problem is that I dont understand the syntax. For instance, how to return the class member function ".to_csv" in "save_to_file()"? How does "save_to_file()" look like? Which args does it take?
Of course, I could use a lambda instead of defining each function. But I want to understand how to define functions first. The next step with lambdas, I can figure out myself.
I'd make sure this is actually what you want to do, but assuming it is, you can just write a function that calls functions (and passes through arguments), like this:
def process_df(df, function, *args, **kwargs):
function(df, *args, **kwargs)
And define your two actions.
def print_to_screen(df):
print df
def save_to_file(df, filename):
df.to_csv(filename)
Then you can use these as you like:
In [193]: df = pd.DataFrame([[1,2,3],[2,4,5]], columns=['a','b','c'])
In [197]: process_df(df, print_to_screen)
a b c
0 1 2 3
1 2 4 5
In [198]: process_df(df, save_to_file, 'temp.csv')
#writes temp.csv
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments