【问题标题】:MemoryError when opening CSV file with pandas使用熊猫打开 CSV 文件时出现内存错误
【发布时间】:2020-07-31 17:32:20
【问题描述】:

我尝试使用 pandas 打开一个 CSV 文件,但出现 MemoryError。该文件约为300mb。当我使用较小的文件时,一切正常。

我正在使用具有 64GB RAM 的 Windows 10。我已经尝试在 Pycharm 中更改自定义 VM 选项(“帮助”>>“编辑自定义 VM 选项”)并设置更高的内存数量,但它仍然不起作用

import pandas as pd

df = pd.read_csv('report_OOP_Full.csv')

# I tried to add the following line but doesnt help
# df.info(memory_usage='deep')

MemoryError: Unable to allocate 344. MiB for an array with shape (14, 3216774) and data type float64

进程以退出代码 1 结束

【问题讨论】:

  • 是否需要导入所有行?
  • 是的,如果可能的话!
  • 您知道您的列中的数据类型是什么吗?您可以尝试在pd.read_csv(fname, dtype=<<mapping_dictionary>>) 中指定它们,这有时有助于减少内存使用量。问题有所不同,但解决方案可能对您有所帮助:stackoverflow.com/questions/49684951/…
  • 谢谢肯!是的,我有花车和字符串。我会检查那个链接,看看它是否有帮助!谢谢!

标签: pandas


【解决方案1】:

这可能不是最有效的方法,但试试吧。 根据您的 RAM 可用性减少或增加块大小。

chunks = pd.read_csv('report_OOP_Full.csv', chunksize=10000)
i = 0
chunk_list = []
for chunk in chunks:
    i += 1
    chunk_list.append(chunk)
    df = pd.concat(chunk_list, sort = True)

如果这不起作用。试试这个:

chunks = pd.read_csv('report_OOP_Full.csv', chunksize=10000)
i = 0
chunk_list = []
for chunk in chunks:
    if i >= 10:
        break
    i += 1
    chunk_list.append(chunk)
    df1 = pd.concat(chunk_list, sort = True)


chunks = pd.read_csv('report_OOP_Full.csv', skiprows = 100000, chunksize=10000)
i = 0
chunk_list = []
for chunk in chunks:
    if i >= 10:
        break
    i += 1
    chunk_list.append(chunk)
    df2 = pd.concat(chunk_list, sort = True)


d3 = pd.concat([d1,d2], sort = True)

skiprows 是根据前一个数据帧已读入的行数计算得出的。
这将在加载 10 个块后中断。将此存储为 df1。并从块 11 开始再次读取文件,然后再次附加。

我了解您正在处理一些大数据。我鼓励你看看我发现的这个函数。下面的链接解释了它是如何工作的。 此功能的功劳在这里: credit

def reduce_mem_usage(df):
    start_mem = df.memory_usage().sum() / 1024**2
    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))

    for col in df.columns:
        col_type = df[col].dtype
    if col_type != object:
            c_min = df[col].min()
            c_max = df[col].max()
            if str(col_type)[:3] == 'int':
                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
                    df[col] = df[col].astype(np.int8)
                elif c_min > np.iinfo(np.uint8).min and c_max < np.iinfo(np.uint8).max:
                    df[col] = df[col].astype(np.uint8)
                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
                    df[col] = df[col].astype(np.int16)
                elif c_min > np.iinfo(np.uint16).min and c_max < np.iinfo(np.uint16).max:
                    df[col] = df[col].astype(np.uint16)
                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
                    df[col] = df[col].astype(np.int32)
                elif c_min > np.iinfo(np.uint32).min and c_max < np.iinfo(np.uint32).max:
                    df[col] = df[col].astype(np.uint32)                    
                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
                    df[col] = df[col].astype(np.int64)
                elif c_min > np.iinfo(np.uint64).min and c_max < np.iinfo(np.uint64).max:
                    df[col] = df[col].astype(np.uint64)
            else:
                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
                    df[col] = df[col].astype(np.float16)
                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
                    df[col] = df[col].astype(np.float32)
                else:
                    df[col] = df[col].astype(np.float64)

    end_mem = df.memory_usage().sum() / 1024**2
    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))
return df

这将确保您的数据框在使用它时使用尽可能低的内存。

【讨论】:

    【解决方案2】:

    我想另一种方法是只打开第一列中具有相同值的原始数据(在本例中为字符串,1 个字母)。我不知道这是否可能。例如:

    A 4 5 6 3

    A 3 4 5 7

    A 2 1 4 9

    A 1 1 8 7

    B 1 2 3 1

    B 2 2 3 3

    C 1 2 1 2

    首先打开一个只有以 "A" 开头的原始数据的数据框,然后对 "B" 、 "C" 等执行相同操作。我不知道这是否可能,但它会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 2018-10-24
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 2014-06-05
      相关资源
      最近更新 更多