【问题标题】:PyTables read random subsetPyTables 读取随机子集
【发布时间】:2014-01-29 03:47:25
【问题描述】:

是否可以从 HDF5 中读取随机的行子集(通过 pyTables 或者最好是 pandas)?我有一个包含数百万行的非常大的数据集,但只需要几千个样本进行分析。那么从压缩的 HDF 文件中读取呢?

【问题讨论】:

    标签: python pandas hdf5 pytables


    【解决方案1】:

    使用HDFStore的文档是here,压缩文档是here

    0.13 支持通过构造索引进行随机访问

    In [26]: df = DataFrame(np.random.randn(100,2),columns=['A','B'])
    
    In [27]: df.to_hdf('test.h5','df',mode='w',format='table')
    
    In [28]: store = pd.HDFStore('test.h5')
    
    In [29]: nrows = store.get_storer('df').nrows
    
    In [30]: nrows
    Out[30]: 100
    
    In [32]: r = np.random.randint(0,nrows,size=10)
    
    In [33]: r
    Out[33]: array([69, 28,  8,  2, 14, 51, 92, 25, 82, 64])
    
    In [34]: pd.read_hdf('test.h5','df',where=pd.Index(r))
    Out[34]: 
               A         B
    69 -0.370739 -0.325433
    28  0.155775  0.961421
    8   0.101041 -0.047499
    2   0.204417  0.470805
    14  0.599348  1.174012
    51  0.634044 -0.769770
    92  0.240077 -0.154110
    25  0.367211 -1.027087
    82 -0.698825 -0.084713
    64 -1.029897 -0.796999
    
    [10 rows x 2 columns]
    

    要包含附加条件,您可以这样做:

    # make sure that we have indexable columns
    df.to_hdf('test.h5','df',mode='w',format='table',data_columns=True)
    
    # select where the index (an integer index) matches r and A > 0
    In [14]: r
    Out[14]: array([33, 51, 33, 95, 69, 21, 43, 58, 58, 58])
    
    In [13]: pd.read_hdf('test.h5','df',where='index=r & A>0')
    Out[13]: 
               A         B
    21  1.456244  0.173443
    43  0.174464 -0.444029
    
    [2 rows x 2 columns]
    

    【讨论】:

    • 是否可以在read_hdf 中包含其他where 条件?例如,如果我想采样 10 个 positive 数字?
    • 谢谢,但这不是我的意思。我需要 10 个正数,但您的示例仅返回 2(您从 10 个样本中返回正数)。我最终使用了生成器并从块中采样。
    • 没有直接的方法可以做到这一点;只需选择更多的数字开始并丢弃不需要的数字。
    • 如果我的 HDF5 文件是“固定的”,我是不是运气不好?
    • 读回来再写出来(指定写上的格式)
    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 2017-05-19
    • 2019-06-15
    • 1970-01-01
    相关资源
    最近更新 更多