在进行某些查询时,HDFStore
Pandas
模块中似乎存在错误,但我无法找到解决方法。也就是说,似乎pd.HDFStore.select
在内部将其他有效字符串重新格式化为错误的语法。例如,由于某种原因,字符串"03"
会将where
语句输入为"0 3"
,并返回syntax
错误。
p1 = np.random.randint(0,100,(100,2))
p2 = np.random.choice(np.array(range(1990,2010)),100).reshape((100,1))
df = pd.DataFrame(np.concatenate([p2,p1],axis=1), columns = ['year', 'value1', 'value2'])
df.year2 = df.year.astype(str).str[2:]
data_path = "C:/Users/.../some path"
with pd.HDFStore("/".join([data_path, 'sampleData.h5']), 'w') as store:
store.put('example', df, format='table')
query1 = 'year2<={0}'.format('99')
query2 = "year2=={0} | year2=={1}".format('01', '02')
with pd.HDFStore("/".join([data_path, 'sampleData.h5']), 'r') as store:
df_load = store.select('example', where=[query1],columns = ['year', 'year2', 'value1'])
In [111]: %paste
with pd.HDFStore("/".join([data_path, 'sampleData.h5']), 'r') as store:
df_load = store.select('example', where=[query2],columns = ['year', 'year2', 'value1'])
## -- End pasted text --
File "<unknown>", line 1
(year2 ==0 1 or year2 ==0 2 )
^
SyntaxError: invalid syntax
是否有人知道不会将"01"
分为"0 1"
的锻炼?
答案 0 :(得分:0)
根据Pandas关于HDF5 queries的文件,不推荐上述方法(即n=5; query="blah blah %d" %n
),大概是因为解释器问题。而是使用%r
格式化程序传递。
因此,对于上面的例子,你会做
query2 = "year2==%r | year2==%r" %('01', '02')
with pd.HDFStore("/".join([data_path, 'sampleData.h5']), 'r') as store:
df_load = store.select('example', where=[query2],columns = ['year', 'year2', 'value1'])
哪个有效。