Home > Net >  How can we call dataframe functions like (mean, median, mode, min ...) dynamically
How can we call dataframe functions like (mean, median, mode, min ...) dynamically

Time:12-06

fields = {'rule1':'min','rule2':'max'}

For example:

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

CodePudding user response:

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}')

CodePudding user response:

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)())

  • Related