【问题标题】:Python Read HDF5 Rows Where Index Not in ListPython读取索引不在列表中的HDF5行
【发布时间】:2017-03-11 14:48:14
【问题描述】:

我使用以下 Python/Pandas 代码从 HDF 表中读取行的随机子集:

hdf_store = pd.HDFStore('path_to_data.h5')
total_rows = hdf_store.get_storer('hdf_table_name').nrows

num_rows = int(total_rows * .25)
row_indices = np.random.randint(0,rows_indices,size=num_rows)

my_df = pd.read_hdf(hdf_store, 'hdf_table_name', where=pd.Index(row_indices))

稍后在程序中,我想从 HDF5 表中提取其余的数据行。但以下引发了错误:

rest_of_rows = pd.read_hdf(hdf_store, 'hdf_table_name',
   where=pd.Index(not in (row_indices)))

rest_of_rows = pd.read_hdf(hdf_store, 'hdf_table_name',
   where=not pd.Index(row_indices))

有没有办法通过不在索引列表中的记录来提取 HDF 行?

由于该表比我的 RAM 大,我想避免预先从 HDF 中提取所有行(即使是块),然后将其拆分以同时保存两个表。我可以将索引映射到另一列,以及不在该列映射值中的行的子集。但这大概比直接查询索引要慢很多。

【问题讨论】:

    标签: python pandas indexing dataframe hdf5


    【解决方案1】:

    您可以使用Index.difference 方法。

    演示:

    # randomly select 25% of index elements (without duplicates `replace=False`)
    sample_idx = np.random.choice(np.arange(total_rows), total_rows//4, replace=False)
    
    # select remaining index elements
    rest_idx = pd.Index(np.arange(total_rows)).difference(sample_idx)
    
    # get rest rows by index
    rest = store.select('hdf_table_name', where=rest_idx)
    

    PS 可选地,您可能希望以块的形式选择其余行...

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 2016-02-24
      • 2015-03-26
      • 2021-04-20
      • 2013-03-30
      相关资源
      最近更新 更多