Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change pandas category type using a dtype dict?

Tags:

pandas

Instead of doing :

for col in df.columns : 
   df[col]= df[col].astype('category')

Am doing this :

dtype0= {'brand': np.dtype('int64'),
 'category': np.dtype('int64'),
 'chain': np.dtype('int64'),
 'company': np.dtype('int64'),
 'date': np.dtype('O'),
 'dept':  pandas.types.dtypes.CategoricalDtype,
 'id': np.dtype('int64')}

df= df.astype(dtype0)

However, it does not work. Just wondering, how to change into category using the dictionnary.

like image 310
tensor Avatar asked Jan 07 '17 02:01

tensor


1 Answers

Previous answer is not correct. We can cast after creating the dataframe.

Solution is (for the record for other people stuck here): Pandas 0.19.1

dtype0= {'brand': 'int64',
 'category': 'int64',
 'chain': 'int64',
 'company': 'int64',
 'date': 'str',
 'dept':  'category',
 'id': 'int64'}
df= df.astype(dtype0)

casting works here.

like image 91
tensor Avatar answered Oct 14 '22 15:10

tensor