The following code returns all NaN's instead of "given" categories:
Code Sample, a copy-pastable example if possible
In [25]: df = pd.DataFrame({'a':['aa','bb','cc','dd']})
In [26]: df
Out[26]:
a
0 aa
1 bb
2 cc
3 dd
In [27]: df.a.astype('category', categories=[0,1,2,3])
Out[27]:
0 NaN
1 NaN
2 NaN
3 NaN
Name: a, dtype: category
Categories (4, int64): [0, 1, 2, 3]
In [28]: df.a.astype('category', categories=['0','1','2','3'])
Out[28]:
0 NaN
1 NaN
2 NaN
3 NaN
Name: a, dtype: category
Categories (4, object): [0, 1, 2, 3]
Expected Output
a
0 0
1 1
2 2
3 3
Name: a, dtype: category
Categories (4, object): [0, 1, 2, 3]
output of pd.show_versions()
In [29]: pd.show_versions()
INSTALLED VERSIONS
------------------
commit: None
python: 3.5.1.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: en_US
pandas: 0.18.1
nose: 1.3.7
pip: 8.1.2
setuptools: 25.1.1
Cython: 0.24.1
numpy: 1.11.1
scipy: 0.18.0
statsmodels: None
xarray: 0.7.2
IPython: 4.2.0
sphinx: 1.4
patsy: 0.4.1
dateutil: 2.5.3
pytz: 2016.6.1
blosc: None
bottleneck: 1.1.0
tables: 3.2.3
numexpr: 2.6.1
matplotlib: 1.5.1
openpyxl: 2.3.5
xlrd: 1.0.0
xlwt: None
xlsxwriter: 0.9.3
lxml: 3.6.1
bs4: 4.5.0
html5lib: 0.999999999
httplib2: None
apiclient: None
sqlalchemy: 1.0.14
pymysql: None
psycopg2: None
jinja2: 2.8
boto: None
pandas_datareader: 0.2.1
Comment From: jreback
this is correct..
In [6]: Series(['aa','bb','cc','dd']).astype('category',categories=['aa','dd','c','b'])
Out[6]:
0 aa
1 NaN
2 NaN
3 dd
dtype: category
Categories (4, object): [aa, dd, c, b]
you might be looking rename categories. which simply substitutes the categories names.
In [5]: df.a.astype('category').cat.rename_categories([0,1,2,3])
Out[5]:
0 0
1 1
2 2
3 3
dtype: category
Categories (4, int64): [0, 1, 2, 3]