How can we call dataframe functions like (mean, median, mode, min …) dynamically

How can we call dataframe functions like (mean, median, mode, min …) dynamically

Problem Description:

fields = {‘rule1′:’min’,’rule2′:’max’}

For example:

for key, value in fields.items():
    Dataframe.{value}()

Solution – 1

You can try getattr as below

fields = {
    'mean': df.mean,
    'median': df.median,
    'mode': df.mode,
    'min': df.min,
    'max': df.max
}

for key, value in fields.items():
        # Call the method using getattr()
        result = getattr(df, value)()
        print(f'The result of calling {key}() is: {result}')

Solution – 2

You can accomplish this with getattr. For example:

import pandas as pd

df = pd.DataFrame([[1]])
for f in ('min', 'max'):
  print(getattr(df, f)())

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject