我知道如何在 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' AND 'B > 0' AND '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]
关于python - 在 hdfstore 中使用 OR 选择 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20502996/