1

When I use getattr() to dynamically access the mean of a pandas dataframe or series, it returns a Series.mean object. However, when I use df.mean() to access the mean, it returns a float.

Why doesn't getattr() return the same thing that the normal method does?

Minimal reproducible code:

import pandas as pd
import numpy as np

s = pd.Series(np.random.randn(5))
print(getattr(s, "mean"))
>>> <bound method Series.mean of 
>>> 0    1.158042
>>> 1   -0.586821
>>> 2   -1.976764
>>> 3    1.722072
>>> 4    1.129570
print(s.mean())
>>> dtype: float64>
>>> 0.28921963496328584

I have used dir(getattr(s, "mean")) to attempt to get the mean value, but can't figure out which attribute, if any, will get me the float mean value.

conchoecia
  • 491
  • 1
  • 8
  • 25

1 Answers1

6

Since returned atttribute by getattr is callable, try:

print(getattr(s, "mean")())
Sahil Dahiya
  • 721
  • 1
  • 5
  • 12