我有一个数据帧作为表保存到HDF5中,但是当select语句有浮点数时,where子句会出错(它确实可以处理字符串)。在Ubuntu12.04LTS上有最新版本的熊猫0.12。

>>> dim_hdf.select(store_name)
    desc  rowid
0    NaN    NaN
1    1.0      1
2    2.0      2
3    3.0      3
4    4.0      4
5    5.0      5
6    6.0      6
7    7.0      7
8    8.0      8
9    9.0      9
10  10.0     10

>>> dim_hdf.select(store_name).dtypes
desc      object
rowid    float64
dtype: object

>>> dim_hdf.root.dim_29.table
/dim_29/table (Table(11,)) ''
  description := {
  "index": Int64Col(shape=(), dflt=0, pos=0),
  "desc": StringCol(itemsize=4, shape=(), dflt='', pos=1),
  "rowid": Float64Col(shape=(), dflt=0.0, pos=2)}
  byteorder := 'little'
  chunkshape := (3276,)
  autoindex := True
  colindexes := {
    "index": Index(6, medium, shuffle, zlib(1)).is_csi=False,
    "rowid": Index(6, medium, shuffle, zlib(1)).is_csi=False,
    "desc": Index(6, medium, shuffle, zlib(1)).is_csi=False}

但选择出错(对字符串有效):
>>> dim_hdf.select(store_name, where=[('rowid','=', 1.0)])
Empty DataFrame
Columns: [desc, rowid]
Index: []

>>> dim_hdf.select(store_name, where=[('rowid','=', '1.0')])
Empty DataFrame
Columns: [desc, rowid]
Index: []

>>> dim_hdf.select(store_name, where=[('desc','=', '1.0')])
  desc  rowid
1  1.0      1

我是做错什么了还是这是个错误?
谨致问候,
卡斯特

最佳答案

我几乎百分之百确定这是PyTables中一个非常微妙的bug(>=2.3)。请看这里:https://github.com/PyTables/PyTables/issues/282
似乎当在浮动列上进行选择时,它有一个索引,并且
第一(0)个元素中有一个np.nan,选择不起作用。
np.nan不在第0位或没有索引时,则
选择正常工作。
解决方法是:在第一行写一个“伪”值,或者
没有该列的索引。

In [13]: df = DataFrame(dict(cols = range(6), values = range(6)), dtype='float64')

In [14]: df['cols'] = (df['cols']+10).apply(str)

In [15]: df.iloc[0] = np.nan

In [18]: df
Out[18]:
   cols  values
0   NaN     NaN
1  11.0       1
2  12.0       2
3  13.0       3
4  14.0       4
5  15.0       5

# write w/o the index on that particular column
In [16]: df.to_hdf('test.h5','df',mode='w',table=True,data_columns=True,index=['cols'])

In [17]: pd.read_hdf('test.h5','df',where=[('values','>',2.0)])
Out[17]:
   cols  values
3  13.0       3
4  14.0       4
5  15.0       5

10-08 07:18
查看更多