【问题标题】:How to query an HDF store using Pandas/Python如何使用 Pandas/Python 查询 HDF 存储
【发布时间】:2018-05-02 08:38:30
【问题描述】:

为了管理我在分析时消耗的 RAM 量,我有一个存储在 hdf5 (.h5) 中的大型数据集,我需要使用 Pandas 高效地查询这个数据集。

数据集包含一组应用的用户性能数据。我只想从 40 个可能的字段中提取几个字段,然后将结果数据框过滤到仅使用我感兴趣的少数应用之一的用户。

# list of apps I want to analyze
apps = ['a','d','f']

# Users.h5 contains only one field_table called 'df'
store = pd.HDFStore('Users.h5')

# the following query works fine
df = store.select('df',columns=['account','metric1','metric2'],where=['Month==10','IsMessager==1'])

# the following pseudo-query fails
df = store.select('df',columns=['account','metric1','metric2'],where=['Month==10','IsMessager==1', 'app in apps'])

我意识到字符串“应用程序中的应用程序”不是我想要的。这只是我希望实现的类似 SQL 的表示。我似乎无法以任何我尝试的方式传递字符串列表,但一定有办法。

现在我只是在不带此参数的情况下运行查询,然后在后续步骤中过滤掉我不想要的应用程序

df = df[df['app'].isin(apps)]

但这效率要低得多,因为所有应用程序都需要先加载到内存中,然后才能删除它们。在某些情况下,这是个大问题,因为我没有足够的内存来支持整个未过滤的 df。

【问题讨论】:

    标签: python pandas hdfs


    【解决方案1】:

    你已经很接近了。

    In [1]: df = DataFrame({'A' : ['foo','foo','bar','bar','baz'],
                            'B' : [1,2,1,2,1], 
                            'C' : np.random.randn(5) })
    
    In [2]: df
    Out[2]: 
         A  B         C
    0  foo  1 -0.909708
    1  foo  2  1.321838
    2  bar  1  0.368994
    3  bar  2 -0.058657
    4  baz  1 -1.159151
    
    [5 rows x 3 columns]
    

    将商店写成表格(注意在 0.12 中您将使用table=True,而不是format='table')。建表时记得指定要查询的data_columns(也可以data_columns=True

    In [3]: df.to_hdf('test.h5','df',mode='w',format='table',data_columns=['A','B'])
    
    In [4]: pd.read_hdf('test.h5','df')
    Out[4]: 
         A  B         C
    0  foo  1 -0.909708
    1  foo  2  1.321838
    2  bar  1  0.368994
    3  bar  2 -0.058657
    4  baz  1 -1.159151
    
    [5 rows x 3 columns]
    

    master/0.13 中的语法,isin 是通过query_column=list_of_values 完成的。这以字符串的形式显示在哪里。

    In [8]: pd.read_hdf('test.h5','df',where='A=["foo","bar"] & B=1')
    Out[8]: 
         A  B         C
    0  foo  1 -0.909708
    2  bar  1  0.368994
    
    [2 rows x 3 columns]
    

    0.12 中的语法,这必须是一个列表(其中和条件)。

    In [11]: pd.read_hdf('test.h5','df',where=[pd.Term('A','=',["foo","bar"]),'B=1'])
    Out[11]: 
         A  B         C
    0  foo  1 -0.909708
    2  bar  1  0.368994
    
    [2 rows x 3 columns]
    

    【讨论】:

      猜你喜欢
      • 2015-01-26
      • 2018-03-11
      • 2020-07-27
      • 2017-12-15
      • 2016-02-02
      • 2021-07-30
      • 2018-07-31
      • 2022-11-15
      相关资源
      最近更新 更多