python Pandas 针对 ubyte 数据的优化 (0..255)

python Pandas optimization for ubyte data (0..255)

如何将 Pandas df 优化为 ubyte 数据类型 (0..255)? (整数默认为 int64)

如果我将数据转换为分类类型,df 会使用更少的内存吗?

或者唯一的优化方法——使用 NumPy 而不是 Pandas?

对于 0..255 范围内的无符号整数数据,您可以将内存存储从默认 int64(8 字节)减少为使用 uint8(1 字节)。您可以参考 this article 的示例,其中内存使用量从 1.5MB 大幅减少到 332KB(大约五分之一)。

对于分类类型,由于 Pandas 将分类列存储为对象,因此这种存储方式不是最优的。原因之一是它创建了一个指向列的每个值的内存地址的指针列表。有关详细信息,请参阅 this article

要使用uint8,您可以在输入数据时使用,例如在 pd.read_csv 调用期间,您指定具有 uint8 类型的输入列的数据类型。 (参见 first article for an example). If you already have your data loaded and you want to convert the dataframe columns to use uint8, you can use the Series.astype() or DataFrame.astype() 函数,其语法如 .astype('uint8').