如何使用dtype dict更改pandas类别类型?

时间:2017-01-07 02:41:59

标签: pandas

而不是:

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

我这样做:

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)

然而,它不起作用。只是想知道如何使用词典更改为类别。

2 个答案:

答案 0 :(得分:4)

以前的答案不正确。我们可以在创建数据帧后进行投射。

解决方案是(对于其他人的记录): 熊猫0.19.1

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

施法在这里工作。

答案 1 :(得分:-2)

只有在读取数据时才能这样做

data = pd.read_csv('mypath.csv', dtypes = mydict)