python – 在hdfstore中使用OR选择pandas

我知道如何在pandas HDFStore.select中使用AND类型的查询,但是我如何使用OR?

例如,我有以下代码

import pandas as pd
df1 = pd.DataFrame({'A': randn(100),
                'B': randn(100),
                'C': randn(100).cumsum()},
                index=pd.bdate_range(end=pd.Timestamp('20131031 23:59:00'), periods=100))
df1.to_hdf('testHDF.h5', 'testVar1', format='table', data_columns=True, append=True)

然后我可以使用以下内容从此数据集中部分加载

store = pd.HDFStore('testHDF.h5')
store.select('testVar1', [pd.Term('index', '>=', pd.Timestamp('20131017')), 'A > 0'])

要么

store.select('tableVar2', where=('A > 0', 'B > 0', 'index >= 20131017'))

显然,它使用AND来组合我提供的所有条件,例如(‘A> 0’和’B> 0’和’index> = 20131017’)

我的问题是,我如何使用OR,例如返回的结果是(‘A> 0’OR’B> 0’)?

谢谢你的帮助

最佳答案 在0.12中,您必须连续选择多个条件的结果(请记住,您可能会生成重复项)

In [9]: pd.concat([store.select('testVar1', where=('A > 0', 'index >= 20131017')),
                   store.select('testVar1', where=('B > 0', 'index >= 20131017'))]).drop_duplicates().sort_index()
Out[9]: 
                   A         B          C
2013-10-17  0.156248  0.085911  10.238636
2013-10-22 -0.125369  0.335910  10.865678
2013-10-23 -2.531444  0.690332  12.335883
2013-10-24 -0.266777  0.501257  13.529781
2013-10-25  0.815413 -0.629418  14.690554
2013-10-28  0.383213 -0.587026  13.589094
2013-10-31  1.897674  0.361764  14.595062

[7 rows x 3 columns]

在0.13 / master(0.13rc1已经出来!)中,你可以做一个非常自然的查询

In [10]: store.select('testVar1', where='(A > 0 | B > 0) & index >= 20131017')
Out[10]: 
                   A         B          C
2013-10-17  0.156248  0.085911  10.238636
2013-10-22 -0.125369  0.335910  10.865678
2013-10-23 -2.531444  0.690332  12.335883
2013-10-24 -0.266777  0.501257  13.529781
2013-10-25  0.815413 -0.629418  14.690554
2013-10-28  0.383213 -0.587026  13.589094
2013-10-31  1.897674  0.361764  14.595062

[7 rows x 3 columns]
点赞