python – 使用点符号(如DataFrame)访问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

解决方法:

我通过重载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

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...