gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:35:40 28 4
gpt4 key购买 nike

我的问题涉及优化 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com