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