Pandas Access Dot Series Element such as DataFrame

Is it possible to access a series element through dot notation instead of parentheses?

s = pandas.Series(dict(a=4, b=4)) print s['a'] # works print sa # fails 

How can we do this with a DataFrame:

 df = pandas.DataFrame([dict(a=4, b=4), dict(a=4, b=4)]) print df['a'] # works print df.a # works 
+4
source share
2 answers

I get the behavior by overloading the Series .__ get_attr__ method:

 def my__getattr__(self, key): # If attribute is in the self Series instance ... if key in self: # ... return is as an attribute return self[key] else: # ... raise the usual exception raise AttributeError("'Series' object has no attribute '%s'" % key) # Overwrite current Series attributes 'else' case pandas.Series.__getattr__ = my__getattr__ 

Then I can access the Seriee elements with attributes:

 xx = pandas.Series(dict(a=44, b=55)) xx.a 
+3
source

Impossible. You can convert a series to a single-column DataFrame.

-1
source

Source: https://habr.com/ru/post/1433723/


All Articles