Pandas 如何将类别的基础表示设置为uint8?

Pandas 如何将类别的基础表示设置为uint8?,pandas,categorical-data,Pandas,Categorical Data,我有大量的基因组学数据集,有两个分类栏“染色体”和“链”。我知道两者的值都不会超过25个,因此我想使用uint8作为类别的基础数据。我该怎么做呢?我想你可以用numpy将你的专栏直接转换到uint8 df = pd.DataFrame({'Strand': [123, 208, 213, 111]}) df['Strand'] = df['Strand'].astype(np.uint8) df.dtypes Strand uint8 dtype: object 如果将列进一步强制转换为

我有大量的基因组学数据集,有两个分类栏“染色体”和“链”。我知道两者的值都不会超过25个,因此我想使用uint8作为类别的基础数据。我该怎么做呢?

我想你可以用numpy将你的专栏直接转换到uint8

df = pd.DataFrame({'Strand': [123, 208, 213, 111]})
df['Strand'] = df['Strand'].astype(np.uint8)
df.dtypes
Strand    uint8
dtype: object
如果将列进一步强制转换为字符串,则会将数据类型转换为uint64:

df['Strand'] = pd.Categorical(df['Strand']).
[123, 208, 213, 111] Categories (4, uint64): [111, 123, 208, 213]

正确的答案似乎是熊猫默认使用正确的int大小!参见
c.cat.codes
其中c是一个分类列:)