【问题标题】:How to use the `.loc` method from pandas on a custom class object?如何在自定义类对象上使用 pandas 的`.loc` 方法?
【发布时间】:2019-04-15 13:29:37
【问题描述】:

我一直在浏览 pandas https://github.com/pandas-dev/pandas/blob/master/pandas/core/generic.py 的源代码,但我无法弄清楚它们在哪里实际实现了 .loc 切片方法。我正在开发一个包含pd.DataFrames 的包装器。为了这个问题,我们称之为DataFrameCollection。我不想继承所有的方法所以我不想做class DataFrameCollection(pd.DataFrame): pass

有谁知道哪个代码负责pd.DataFrame 对象的.loc 方法以及如何在自定义对象上使用它?

基本上我希望能够做到以下几点:

dfc_iris =  DataFrameCollection(" a bunch of dataframes")
dfc_iris.loc[idx_obsvs, :]

【问题讨论】:

标签: python pandas class object indexing


【解决方案1】:

loc 属性是几个索引器之一,请参阅pandas.core.indexing module,特别是get_indexers_list() function

# the supported indexers
def get_indexers_list():


    return [
        ('ix', _IXIndexer),
        ('iloc', _iLocIndexer),
        ('loc', _LocIndexer),
        ('at', _AtIndexer),
        ('iat', _iAtIndexer),
    ]

每个类都定义在同一个模块中。

那个函数is used to add attributes to the NDFrame class,它是pandas.DataFrame的基类。 get_indexers_list() 结果中的每个类都是added as a property object

所以要重用对象类型,您可以添加属性,必要时使用相同的代码;将相同的类方法添加到您的类中

@classmethod
def _create_indexer(cls, name, indexer):
    """Create an indexer like _name in the class."""
    if getattr(cls, name, None) is None:
        _indexer = functools.partial(indexer, name)
        setattr(cls, name, property(_indexer, doc=indexer.__doc__))

然后添加索引器

# install the indexes
for _name, _indexer in indexing.get_indexers_list():
    DataFrameCollection._create_indexer(_name, _indexer)

给定 DataFrameCollection 类的 dfcollection 实例,dfcollection.loc 将导致 _LocIndexer('loc', dfcollection) 被调用并返回。

请研究pandas.core.indexing 中的剩余代码,以了解每个索引器如何期望在您的DataFrameCollection 实例上找到信息;它是索引器方法中的 self.obj 引用。

例如,dfcollection.loc[...] 被转换为_LocationIndexer.__getitem__(),它代表_LocIndexer._is_scalar_access()_LocIndexer._getitem_scalar()_NDFrameIndexer._getitem_tuple()_LocIndexer._getitem_axis(),连同这些委托给的方法,需要访问 at至少数据帧上的.axes.ndim._get_value()._get_axis_name()._get_axis_number()._get_axis()._reindex_with_indexers()._take() 属性和方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-07
    • 2016-08-14
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多