首页 > 解决方案 > 使用 Pandas to_hdf 时,是否可以为不规则张量指定 vlen special_dtype / vlarray 的列数据类型?

问题描述

我有一个 Pandas 列,其中包含不同大小的 numpy 数组或列表。如果我尝试使用 to_hdf 将数据帧转换为 hdf5 ,我会收到消息说

PerformanceWarning: 
your performance may suffer as PyTables will pickle object types that it cannot
map directly to c-types [inferred_type->mixed-integer,key->block0_values]

我猜这是因为 pandas 列中参差不齐的张量。HDpy 确实具有用于不规则张量的特殊数据类型。

http://docs.h5py.org/en/stable/special.html#arbitrary-vlen-data

这里的例子

h5f = h5py.File('data.h5', 'w')
dt = h5py.special_dtype(vlen=np.dtype('int32'))
h5f.create_dataset('batch', data=yourData, dtype=dt, compression='gzip', compression_opts=9)

因此,我可以将 pandas df 转换为 numpy,然后分别保存每个 numpy 数组,并使用特殊的 vlen 数据类型存储可变长度列。

我想知道熊猫是否有办法做到这一点。

以下是使用我的一小部分数据的最小示例。它下载并打开一小块数据帧,并将其保存到 hdf5

import requests
import pickle
import numpy as np
import pandas as pd

#Download function for google drive 

def download_file_from_google_drive(id, destination):
    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)    

def get_confirm_token(response):
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            return value

    return None

def save_response_content(response, destination):
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

#download the google drive file 
download_file_from_google_drive('1-0R28Yhdrq2QWQ-4MXHIZUdZG2WZK2qR', 'sample.pkl') 

sampleDF2 = pd.read_pickle('sample.pkl')

sampleDF2.to_hdf( 'pandasList.hdf', 'first', complevel = 9 )

sampleDF2['totalCites2'] = sampleDF2['totalCites2'].apply(lambda x: np.array(x))

sampleDF2.to_hdf( 'pandasNumpy.hdf', 'first', complevel = 9 )

为方便起见,这是一个包含此代码的 colab 笔记本

https://colab.research.google.com/drive/1DjiPsN3MbRWP6NnJwvaAhzy66FNbPVA8

编辑:

正如 hpualj 提到的,Pandas 使用 Pytables 而不是 h5py,所以看起来问题应该是如何使用 vlarray,这是 pytables 存储可变长度数组的方式。

标签: pandasnumpyhdf5h5pypytables

解决方案


推荐阅读