Skip to content

Order of Categories in unordered Categorical causes query bugs in read_hdf #16623

Open
@stoddardg

Description

@stoddardg

Code Sample, a copy-pastable example if possible

df = pd.DataFrame({'idx':[1,2],'val':['A','B']})
df['cat_val'] = pd.Categorical(df['val'], categories=['C','B','A'],ordered=False)
df.to_hdf('test.h5','test',format='table',data_columns=True)

temp_cats = ['A','B']
query_string = "cat_val in %s" % temp_cats
stored_df = pd.read_hdf('test.h5','test',where=query_string)
print(stored_df) # No rows in stored_df

Problem description

The above code prints an empty dataframe but it should print both rows of the original dataframe.

When the categories= argument is not sorted, the where clause of read_hdf does not function as intended. In this case, no rows are returned when limiting to cat_val in ['A','B'], even though both rows of the stored dataframe should be returned.

If I change the second line to df['cat_val'] = pd.Categorical(df['val'], categories=['A','B','C'],ordered=False), then things work as intended.

To check whether it was an issue with the extra category, you can change the second line to df['cat_val'] = pd.Categorical(df['val'], categories=['B','A'],ordered=False) and this time only the cat_val==B row will be selected.

So it seems that the categories argument needs to be sorted, even though this Category is explicitly not ordered. That's easy enough to accomplish but I'm worried that this might indicate a deeper bug in the interaction between HDF and Categoricals.

Expected Output

   idx val cat_val
0    1   A       A
1    2   B       B

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.6.1.final.0
python-bits: 64
OS: Linux
OS-release: 3.10.0-514.16.1.el7.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.20.2
pytest: None
pip: 9.0.1
setuptools: 27.2.0
Cython: None
numpy: 1.12.1
scipy: 0.19.0
xarray: None
IPython: 5.3.0
sphinx: None
patsy: None
dateutil: 2.6.0
pytz: 2016.10
blosc: None
bottleneck: None
tables: 3.3.0
numexpr: 2.6.2
feather: None
matplotlib: 2.0.0
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: 0.999
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.9.5
s3fs: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions