类的属性返回一个数据框,但该数据框属性不适用于类方法

时间:2019-01-10 18:57:53

标签: python pandas properties

尝试编写以下类并提供一些“属性”定义(使用属性装饰器对我来说是全新的,因此部分是探索性的。)

class SNODAS(object):
    """
    Class for working with the SNODAS data from NSIDC: https://nsidc.org/data/g02158

    """

    def __init__(self, base_url='sidads.colorado.edu', base_datastore='/Datasets/noaa/snodas/'):

        self.base_url = base_url
        self.base_datastore = base_datastore
        self._parm_map = {'swe': self.meta.index[0],
                     'depth': self.meta.index[1],
                     'melt': self.meta.index[2],
                     'subl': self.meta.index[3],
                     'blowing_subl': self.meta.index[4],
                     'solid_precip': self.meta.index[5],
                     'liquid_precip': self.meta.index[6],
                     'snow_temp': self.meta.index[7],
                     }

    @property
    def meta(cls):
        if not hasattr(cls, '_meta'):
            cls._meta = pd.read_table('nsidc_var_table.dat').set_index('Parameters')
        return cls._meta

    @property
    def parameters(cls):
        return cls._parm_map.keys()

    @classmethod
    def code(cls, parameter):
        return cls.meta.loc[cls._param_map[parameter]]['Product Code']

当我尝试使用.meta属性时,它像预期的那样表现为数据框:

In [117]: from snodas import SNODAS
In [118]: snds = SNODAS()
In [131]: snds.meta.loc[snds._param_map['swe']]
Out[131]:
Units                           meters
Scale Factor                      1000
Product Code                      1034
Description      Snapshot at 06:00 UTC
Variable Type                    State
Name: SWE, dtype: object

但是,当我尝试在.code类方法中访问它时,出现AttributeError:

In [119]: snds.code('swe')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-119-e5a3ab179363> in <module>
----> 1 snds.code('swe')

~/dev/snodas.py in code(cls, parameter)
     91     @classmethod
     92     def code(cls, parameter):
---> 93         return cls.meta.loc[cls._param_map[parameter]]['Product Code']
     94

AttributeError: 'property' object has no attribute 'loc'

有人可以提供一些关于我在这里做错了什么的见解...

0 个答案:

没有答案