【问题标题】:large filesize difference between `pandas to_json` and `read_json``pandas to_json` 和 `read_json` 之间的大文件大小差异
【发布时间】:2015-11-21 04:43:53
【问题描述】:

设置

这个问题的基础是我正在使用celeryrabbitmq 创建一个分布式HDFStore 消息传递应用程序,它将pandas DataFrames 传递给分布式进程(然后写入HDFStore)。因为jsoncelery 所接受的task serialization protocols 之一,所以pandasto_json()read_json() 功能非常适合完成此任务。

所以我的申请:

  • 点击和 API 并下拉 pandas.DataFrame
  • 使用to_json() 序列化DataFrame
  • 将序列化的值传递给celery worker
  • 使用celery.group 方法在另一侧重新创建DataFrame

问题

我发现当我创建 HDFStore 时,它​​们比我只执行 for 循环并且没有序列化/反序列化对象(使用 json)大 50 倍以上。所以我把celery 去掉了,用一个非常简单的函数重新创建了它,重新创建了这个现象:

import numpy
import pandas
import random


def test_store_size(n_dfs, f_path):
    wj_store = pandas.HDFStore(f_path + 'from_json.h5', mode = 'w')
    nj_store = pandas.HDFStore(f_path + 'from_dfrm.h5', mode = 'w')

    ticks = []

    for i in numpy.arange(n_dfs):

        tag = _rnd_letters(5)
        print "working on " + str(i)

        index = pandas.DatetimeIndex(
                start = '01/01/2000', 
                periods = 1000, 
                freq = 'b'
        )

        df = pandas.DataFrame(
                numpy.random.rand(len(index), 3), 
                columns = ['a', 'b', 'c'], 
                index = index
        )

        nj_store[tag] = df

        stream = df.to_json(
                orient = 'index', 
                date_format = 'iso',
        )

        #stream = df.to_json(orient = 'values')
        wj_df = pandas.read_json(
                stream, 
                typ = 'frame', 
                orient = 'index', 
                dtype = _dtype_cols(df)
        )

        #wj_df = pandas.read_json(stream, convert_dates = False, orient = 'values')
        wj_store[tag] = wj_df

    wj_store.close()
    nj_store.close()

def _rnd_letters(n_letters):
    """Make random tags for the DataFrames"""
    s = 'abcdefghijklmnopqrstuvwxyz'
    return reduce(lambda x, y: x + y, [random.choice(s) for i in numpy.arange(n_letters)])

def _dtype_cols(df):
    """map the types for dytpes"""
    cols = df.columns.tolist()
    return dict([(col, numpy.float) for col in cols])

所以如果你运行以下函数:

In [1]: test_store_size(n_dfs = 10, f_path = '/Users/benjamingross/Desktop/tq-')

以下是HDFStores之间的差距:

所以 21.4 MB 是 365 KB 的 59 倍!!!我正在处理 1,000 个DataFrames,所以我的硬盘驱动器 (400MB) 上似乎很小的空间变成了 24 GB,这现在是一个“大数据”问题(不应该是) .

非常感谢使用to_jsonread_json 进行序列化以“表现”(即序列化前后大小相同)的任何帮助。

我的尝试

我已经尝试了to_json / read_json 中的所有不同参数,包括orient = values,这几乎可以工作,但是我需要序列化indexcolumns,当@ 987654325@ still 最终是原始大小的 60 倍。

【问题讨论】:

    标签: python json serialization pandas celery


    【解决方案1】:

    如果您回顾一下程序的输出,您可能会收到这样的消息:

    In [7]: wj_df.to_hdf('test.h5', 'key')
    PerformanceWarning: 
    your performance may suffer as PyTables will pickle object types that it cannot
    map directly to c-types [inferred_type->unicode,key->axis0] [items->None]
    

    这不是特别明显,但是您的列名被读回为 unicode 而不是 python 字符串 - PyTables 在 python2 中不能很好地处理,所以它回退到酸洗。一个相对简单的解决方法是将列转换为字符串,如下所示。

    wj_df.columns = wj_df.columns.astype(str)
    

    在 GitHub 上有一个针对下面这个问题的问题。

    https://github.com/pydata/pandas/issues/5743

    【讨论】:

    • 奇怪的是我没有收到这些警告,但我正在在我的分布式 celery 应用程序中收到它们。非常感谢您的洞察力、快速修复和现在相同大小的读/写!!
    猜你喜欢
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2010-12-03
    相关资源
    最近更新 更多