0

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?

RickRyan
  • 11
  • 2
  • Just in case if you want to read more about [`getattr`](https://stackoverflow.com/q/4075190/12416453) – Ch3steR Sep 16 '21 at 06:52
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 23 '21 at 12:37

1 Answers1

3

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')
kelvt
  • 949
  • 6
  • 16