访问Pandas Series项,带点符号,如DataFrame

时间:2012-09-12 07:47:21

标签: python pandas

是否可以通过点表示法而不是括号表示法访问Series项目?

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

2 个答案:

答案 0 :(得分:3)

我通过重载Series .__ get_attr__方法来获取行为:

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__

然后我可以使用属性访问Seriee项目:

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

答案 1 :(得分:-1)

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