-2

I have a dataframe and I want to create a list of dataframes produced by the methods .mean(), and .median().

Is there any way to do that like this?:

grouped_df = df.groupby(md)
my_list = [grouped_df.i for i in [mean(), median()]

1 Answers1

1

The most straight forward and no-nonsense way would be:

[grouped_df.mean(), grouped_df.median()]

Any alternative is really unnecessarily more complex:

[i() for i in (grouped_df.mean, grouped_df.median)]
[getattr(grouped_df, i)() for i in ('mean', 'median')]

I'm not sure about the class structure here, but maybe something like this works too:

[i(grouped_df) for i in (df.mean, df.median)]

You'd need to get to a somewhat substantially long list of methods, or a much more dynamic/functional code, to make any of these approaches worth it.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Wow, the getattr approach really worked and allowed me to add more statistics and to apply common methods like .round(3).astype(str). Thank you very much! – Rubén Darksun Jun 24 '21 at 09:20