【问题标题】:Handling a large amount of large data files in pandas在 pandas 中处理大量的大数据文件
【发布时间】:2021-01-12 11:46:02
【问题描述】:

我需要评估来自 DEM 模拟的 1800 个数据文件。每个数据文件在某个时间点有效,并包含一个粒子列表及其温度。我想绘制一段时间内粒子子集的平均温度。 不幸的是,在评估过程中一段时间​​后我的内存不足。每个数据文件大约有 15 MB。这是我所做的:

import pandas as pd
import numpy as np
import linecache
import os as os
import gc

path = "E:/Simulationen/35_1100_700/DEM/post/dump/"

timesList = []      # create empty list for time
TcentralList = []   # create empty list for temperatures 

for files in os.walk(os.path.normpath(path)):
    for file in files[2]:           # files is a tuple with a list of filenames in the third element (index 2) of the tuple
    time = (int(file[0:6])-300000)*0.1+3       # read the timestamps from filenames (first six characters) and convert to time
            timesList.append(time)  # write time to times list for later creation of dataframe

            # Read the headerline (line 9), write items to column title list
            coltitles = [sub.replace('[0]','') for sub in linecache.getline(path+file,9).split()[2:]]
            
            columns=list(range(0,len(coltitles),1))     # list of columns to read
            
            df = pd.read_csv(path+file, sep=' ', skiprows=8, index_col=0, usecols=columns)
            df.columns = coltitles[1:]
            df.index.names = [coltitles[0]]
                      
            T_central = df[df.r.le(0.01) & df.z.ge(0.045) & df.z.lt(0.055)]['f_Temp'].mean(axis=0) # Filter all rows (particles) where radius r is lower/equal than 0.01 m and z is between 0.045 m (greater/equal) and 0.055 m (lower) and average their temperatures 

            # List of average temperatures of central particles for later creation of dataframe
            TcentralList.append(T_central)

我正在读取路径中的所有文件。时间从文件名中获取,转换并存储在列表中 - 我稍后想创建一个带有“时间”和“温度”列的数据框。然后我将数据文件读取到数据框并仅过滤中心区域的粒子,然后平均它们的温度。 数据文件有 17 列。我尝试的第一件事是通过缩短列表“列”来仅读取必要的列,但这并没有减少内存使用量。 然后我尝试手动启动垃圾收集(gc):

gc.collect()
del df
del T_central

这也没有帮助。我还尝试重新初始化 df 和 T_central 以删除对它们的引用

T_central=[]
df=pd.DataFrame()

但没有任何效果。

我没有想法。有人给我提示吗?

干杯, 塞巴斯蒂安

【问题讨论】:

    标签: python pandas dataframe memory garbage-collection


    【解决方案1】:

    无意中找到了解决办法:不是pandas而是linecache.getline()占用了太多内存。手动指定要读取的列和数据框的列标题解决了它。

    【讨论】:

      猜你喜欢
      • 2013-08-28
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 2017-02-09
      • 2017-04-26
      • 1970-01-01
      • 2022-06-11
      相关资源
      最近更新 更多