1

问题:如何创建一个生成器,允许对 pandas HDFStore 对象中的多个列进行迭代?

我正在尝试为 pandas HDFStore 对象创建一个包装类。我试图实现的功能之一是能够通过给定的块大小迭代 HDFStore 中的列组。许多机器学习算法可以运行on-line并且不需要一次所有的数据。

我的第一次尝试是创建一个生成器函数并将开始和停止参数传递给 HDFStore 的 select 方法:

def iterate(self, key, chunksize=50000):
    node = self.store.get_node(key)
    nrows = node.table.nrows
    current = 0
    while current < nrows:
        yield self.store.select(key, start=current, stop=current+chunksize)
        current += chunksize

这很好用,我可以遍历存储中的单个存储列。请注意,为了进行测试,我将每一列都存储在自己的表中。

我的下一步是使用HDFStore.select_as_multiple. 虽然不在文档字符串中,但select_as_multiple似乎也接受了 start 和 stop 参数:

>>> store.select_as_multiple(keys='MachineID', start=0, stop=50000)

<class 'pandas.core.frame.DataFrame'>
Int64Index: 50000 entries, 0 to 49999
Data columns:
MachineID    50000  non-null values
dtypes: int64(1)

按照要求,只返回了 50,000 行。但是,当我传递超过 1 个键/列时,该方法会拉回所有行:

>>> store.select_as_multiple(keys=['MachineID','YearMade'], start=0, stop=50000)

<class 'pandas.core.frame.DataFrame'>
Int64Index: 401125 entries, 0 to 1124
Data columns:
MachineID    401125  non-null values
YearMade     401125  non-null values
dtypes: int64(2)

是否可以使用select_as_multiple拉回指定范围的行而不是所有行?

版本信息:

>>> pd.__version__
'0.10.1'

>>> tables.__version__
'2.4.0'
4

1 回答 1

2

它不起作用,因为没有将开始/停止传递给底层选择。很容易修复。

还意味着添加迭代器支持,将窃取您的功能:)

完成 https://github.com/pydata/pandas/issues/3078

有文档,但本质上是:

for df in store.select('df',chunksize=10000):
    print df
于 2013-03-17T18:55:44.103 回答