I am trying to create a function which would add certain operation on the pandas series. for eg lets say we have this dataframe.
import numpy as np
import pandas as pd
def get_info(df, series, func):
return df[Series].func
data = np.random.randint(10, size= (3, 4))
df = pd.DataFrame(data, columns= ['a', 'b', 'c', 'd'])
a b c d
0 3 1 3 7
1 6 8 8 3
2 9 4 4 9
Here the mean of the 'd' series is df.d.mean() = 6.3.
Instead I want to use my function:
mn = get_info(df, 'd', mean())
But it runs into error NameError: name 'mean' is not defined
Is there any way to achieve this?
CodePudding user response:
Here's what you can do, explanation in the comments:
def get_info(df, series, func):
# check if the method is implemented
if hasattr(df[series], func):
# get the method
f = getattr(df[series], func)
# check if the method is callable
if callable(f):
# call the method
return f()
else:
return "Method is not callable"
else:
return "Method is not implemented"
# example usage
get_info(df, 'd', 'mean')