python - 我什么时候应该使用 Pandas 的 Categorical dtype?

标签 python pandas memory categorical-data

我的问题涉及优化 Pandas 系列的内存使用。文档 note ,

The memory usage of a Categorical is proportional to the number of categories plus the length of the data. In contrast, an object dtype is a constant times the length of the data.



我的理解是 Pandas Categorical data 实际上是到表示类别的唯一(向下转换)整数的映射,其中整数本身占用(大概)比组成 object 的字符串少的字节。数据类型。

我的问题:是否有任何经验法则用于使用时 pd.Categorical不会超过 object 节省内存?前面提到的比例有多直接,它不也取决于系列中每个元素(字符串)的长度吗?

在下面的测试中,pd.Categorical似乎遥遥领先。
import string

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

np.random.seed(444)
%matplotlib inline

def mem_usage(obj, index=False, total=True, deep=True):
    """Memory usage of pandas Series or DataFrame."""
    # Ported from https://www.dataquest.io/blog/pandas-big-data/
    usg = obj.memory_usage(index=index, deep=deep)
    if isinstance(obj, pd.DataFrame) and total:
        usg = usg.sum()
    # Bytes to megabytes
    return usg / 1024 ** 2

catgrs = tuple(string.printable)

lengths = np.arange(1, 10001, dtype=np.uint16)
sizes = []
for length in lengths:
    obj = pd.Series(np.random.choice(catgrs, size=length))
    cat = obj.astype('category')
    sizes.append((mem_usage(obj), mem_usage(cat)))
sizes = np.array(sizes)

fig, ax = plt.subplots()
ax.plot(sizes)
ax.set_ylabel('Size (MB)')
ax.set_xlabel('Series length')
ax.legend(['object dtype', 'category dtype'])
ax.set_title('Memory usage of object vs. category dtype')

enter image description here

尽管如此,对于 n<125,pd.Categorical稍大。
fig, ax = plt.subplots()
ax.plot(sizes[:200])
ax.set_ylabel('Size (MB)')
ax.set_xlabel('Series length')
ax.legend(['object dtype', 'category dtype'])
ax.set_title('Memory usage of object vs. category dtype')

enter image description here

最佳答案

分类 astype 使用较少的内存。然而,一种热编码允许您保持级别的分类排名。您可以分析分类器系数以了解分类数据的行为和预测。

关于python - 我什么时候应该使用 Pandas 的 Categorical dtype?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48256395/

相关文章:

python - NumPy 错误 : Singular matrix

python - 使用 python 正则表达式将文本拆分为多个部分

python - 根据 DateTimeIndex 更新列

c# System.OutOfMemoryException 我该如何解决?

c++ - 没有调用复制构造函数?

python - 如何更改 django-graphql-jwt 中的默认值 'username'

Python计算每个IP每小时的请求率

Pandas 读取带有日期时间段的 csv

python - Pandas DataFrame 步骤图 : where ="post"

python - 如何在 Python 中存储计算结果,这样我的程序就不会对同一事物进行两次计算?