【问题标题】:ValueError: cannot create an OBJECT array from memory bufferValueError:无法从内存缓冲区创建对象数组
【发布时间】:2019-03-29 01:41:49
【问题描述】:

由于在连接 pandas 数据帧时出现内存错误,我决定将 pandas 数据帧以追加模式写入二进制文件,然后读取该二进制文件以获取整个数据帧。

但是,我得到了 'ValueError: cannot create an OBJECT array from memory buffer'

如果所有数据框都有数字列,则不会出现此问题。但是,如果其中一列是字符串(在我的情况下,我的数据框中有很多字符串列),则会弹出此值错误。下面是示例这种情况的代码。取消注释 #works1 或 #works2 以查看没有错误。但是使用#does not work下的数据框会产生ValueError

import pandas as pd
import numpy as np

mtot=0

if os.path.exists('df_all.bin'):
    os.remove('df_all.bin')

for i in range(2):
    #works1
    # df = pd.DataFrame(np.random.randint(100, size=(5, 2)))

    #works2
    # df = pd.DataFrame({'A':[1,2,3], 'B':[1,2,3], 'C':[1.0,2.0,3.0]})
    # df = df.astype(dtype={'A': int, 'B': int, 'C': float})

    #does not work
    df = pd.DataFrame({'A':[1,2,3], 'B':['sample1','sample2','sample3'], 'C':[1.0,2.0,3.0]})
    df = df.astype(dtype={'A': int, 'B': str, 'C': float})

    typ = df.values.dtype
    print('dtype:%s' %typ)

    with open('df_all.bin', 'ab') as f:
        m, n = df.shape
        mtot += m
        f.write(df.values.tobytes())

with open('df_all.bin', 'rb') as f:
    buffer = f.read()
    nparray = np.frombuffer(buffer, dtype=typ)
    data = nparray.reshape(mtot, n)
    whole_df = pd.DataFrame(data=data, columns=list(range(n)))

print(whole_df)
print(whole_df.shape)

os.remove('df_all.bin')

如何摆脱这个ValueError?

谢谢

【问题讨论】:

    标签: python pandas dataframe memory valueerror


    【解决方案1】:

    我的猜测是您使用的是 Python 3,它默认将所有字符串视为 unicode。而Unicode也不容易转成二进制,仅仅是因为单个字符的长度可能是多个字节。

    所以,我认为你应该看看这篇文章:

    Python: convert string to byte array

    将您的字符串数据转换为正确的二进制数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多