处理熊猫中的大量大数据文件

时间:2020-09-26 09:29:50

标签: python pandas dataframe memory garbage-collection

我需要从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()

但没有任何效果。

我没主意了。有人给我一个提示吗?

干杯, 塞巴斯蒂安

1 个答案:

答案 0 :(得分:0)

偶然发现了解决方案:不是linecache.getline()占用了太多的内存。手动指定要读取的列,然后数据框的列标题解决了该问题。

相关问题