【问题标题】:reduce memory dedicated to pandas dtype=object减少专用于 pandas dtype=object 的内存
【发布时间】:2017-09-28 10:33:27
【问题描述】:

是否可以在 Python pandas 中为对象数据类型设置自定义长度? 例如,在我的测试数据框中,具有 dtyp=object 的一列将其大小增加了约 60%。尽管此列中的值只是“Y”或“N”。

“传递 memory_usage='deep' 将启用更准确的内存使用情况报告,说明所包含对象的全部使用情况”

df.info(memory_usage='deep')

dtypes: datetime64ns, float64(8), int16(2), int8(4), object(1) 内存使用量:14.7 MB

df.info()

dtypes: datetime64ns, float64(8), int16(2), int8(4), object(1) 内存使用量:9.2+ MB

这看起来内存效率很低,尽管我找不到任何可以减小大小的选项/数据类型。 (例如,像 int8 而不是 int64)

【问题讨论】:

    标签: python pandas object memory


    【解决方案1】:

    最好的处理方法是使用Categoricals。它将使用int8 来存储值。

    df = pd.DataFrame({'A': np.random.choice(['Y', 'N'], size=10**6)})
    df.info(memory_usage='deep')
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 1000000 entries, 0 to 999999
    Data columns (total 1 columns):
    A    1000000 non-null object
    dtypes: object(1)
    memory usage: 62.9 MB
    

    df['A'] = df['A'].astype('category')
    

    df.info(memory_usage='deep')
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 1000000 entries, 0 to 999999
    Data columns (total 1 columns):
    A    1000000 non-null category
    dtypes: category(1)
    memory usage: 976.8 KB
    

    【讨论】:

    • 谢谢,它解决了一切。只是有些困惑,read_csv 不支持“类别”,但这是由于我的语法错误。
    • @GrinvydasKareiva 欢迎您。对于 read_csv,我认为对分类的支持始于 0.19 版。还要确保您拥有最新版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2013-05-21
    相关资源
    最近更新 更多