4

是否可以通过点符号而不是括号符号访问系列项目?

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

正如我们可以对 DataFrame 做的那样:

df = pandas.DataFrame([dict(a=4, b=4), dict(a=4, b=4)])
print df['a']  # works
print df.a     # works
4

2 回答 2

3

I get the behaviour 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 Seriee items with attributes :

xx = pandas.Series(dict(a=44, b=55))
xx.a
于 2012-09-12T08:55:04.140 回答
-1

不可能。您可以将 Series 转换为单列 DataFrame。

于 2012-09-12T08:30:24.320 回答