【问题标题】:Selecting rows from an HDFStore by index using where使用 where 通过索引从 HDFStore 中选择行
【发布时间】:2013-09-14 18:48:36
【问题描述】:

我有一个数据框,其中 user_ids 存储为 HDFStore 中的索引 frame_table。此 HDF 文件中还有另一个表格,其中包含用户执行的操作。我想抓取 1% 的用户采取的所有行动。程序如下:

#Get 1% of the user IDs
df_id = store.select('df_user_id', columns = ['id'])
1pct_users = rnd.sample(df_id.id.unique(), 0.01*len(df_id.id.unique()))
df_id = df_id[df_id.id.isin(1pct_users)]

现在我想返回并从与 df_user_id 索引相同的 frame_tables 中获取描述这些用户所采取操作的所有附加信息。根据this examplethis question 我做了以下事情:

1pct_actions = store.select('df_actions', where = pd.Term('index', 1pct_users.index))

这只是提供了一个空数据框。事实上,如果我复制并粘贴之前 pandas 文档link 中的示例,我也会得到一个空数据框。在最近的 pandas 中,Term 有什么变化吗?我在熊猫 0.12 上。

我不拘泥于任何特定的解决方案。只要我可以从 df_id 表中查找 hdfstore 索引(速度很快),然后直接从其他帧表中提取这些索引。

【问题讨论】:

    标签: python pandas hdfstore


    【解决方案1】:

    这是 0.12 中的方法。在 0.13 中,where 可以是索引器(例如位置数组,所以这更容易,请参阅(使用 where 掩码选择)[http://pandas.pydata.org/pandas-docs/dev/io.html#高级查询],然后是第二个示例。

    In [2]: df = DataFrame(dict(A=list(range(5)),B=list(range(5))))
    
    In [3]: df
    Out[3]: 
       A  B
    0  0  0
    1  1  1
    2  2  2
    3  3  3
    4  4  4
    
    In [4]: store = pd.HDFStore('test.h5',mode='w')
    
    In [5]: store.append('df',df)
    

    根据某个位置选择并返回一个坐标对象(只是一个包装好的位置数组)

    In [6]: c = store.select_as_coordinates('df', ['index<3'])
    

    接受坐标对象的位置(您可以将它们与任何表格一起使用,这里将是您的“df_action”表格)

    In [7]: store.select('df', where=c)
    Out[7]: 
       A  B
    0  0  0
    1  1  1
    2  2  2
    
    In [8]: c
    Out[8]: <pandas.io.pytables.Coordinates at 0x4669590>
    
    In [9]: c.values
    Out[9]: array([0, 1, 2])
    

    如果您想对此进行操作,则只需在传递给select 之前将您想要的位置分配给坐标对象。 (正如我上面所说,这个“hack”在 0.13 中消失了,你不需要这个中间对象)

    In [8]: c.values = np.array([0,1])
    
    In [9]: store.select('df', where=c)
    Out[9]: 
       A  B
    0  0  0
    1  1  1
    
    store.close()
    

    【讨论】:

    • 完美答案。我误解了 where 参数的格式,并没有意识到它需要像那个坐标那样结构化。我认为它可能是一个松散的定义,作为数组、列表等提供......感谢您清除它。
    • 如果能在 0.13 中成为列表/数组。
    • 我相信文档链接应该是pandas.pydata.org/pandas-docs/stable/…。如果这是正确的,我很乐意编辑答案中的链接。
    猜你喜欢
    • 2015-02-05
    • 2014-04-26
    • 2013-12-28
    • 2017-05-19
    • 2014-06-19
    • 2015-06-12
    • 2021-11-08
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多