这是我先前发布的一个问题的变体,Merging 1300 data frames into a single frame becomes really slow
这一次,我试图合并的框架列明智的,而不是低于对方
我在一个目录中有1300个csv文件
每个文件的第一列都有一个日期,后面是过去20-30年的每日数据,这些数据跨越另外8列
那么像这样,, 数据1.csv
Date source1 source2 source3 source4 source5 source6 source 7 source 8
我有1300个唯一命名的文件,每个文件都有唯一命名的列
我正在尝试使用pandas列方式将所有这些合并到一个数据帧中,不是在下面追加,而是像这样合并左右
import pandas as pd
frame = pd.read_csv(file_path,index_col=0) #this is the location of the first file
for filename in os.listdir(filepath): #filepath has the rest of the files
file_path = os.path.join(filepath, filename)
df = pd.read_csv(file_path,index_col=0)
df = df.groupby(['Date']).first()
df = df.add_prefix(f"{filename}-")
frame = pd.merge(frame, df, how='outer', left_index=True, right_index=True)
length-=1
但是大约在第300个文件的时候,我的代码真的变慢了
我正在按列合并这些文件
我的目标实际上是在30年内拥有一个按日期数计算为1+(1300x8)的海量数据帧
有没有办法在我的电脑内存不足之前加速
代码变慢的原因与linked question:quadratic copy中的问题相同。在每个循环中,您将复制整个现有数据帧加上一些新数据。解决方案是将所有单个数据帧存储在一个列表中,然后在读取所有文件后连接
要用一些示例数据说明该概念,请执行以下操作:
相关问题 更多 >
编程相关推荐