将1300个数据帧按列合并为单个帧的速度非常慢

2024-10-19 16:07:24 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我先前发布的一个问题的变体,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)的海量数据帧

有没有办法在我的电脑内存不足之前加速


Tags: 文件csvthe数据pathsourcedfdate
1条回答
网友
1楼 · 发布于 2024-10-19 16:07:24

代码变慢的原因与linked question:quadratic copy中的问题相同。在每个循环中,您将复制整个现有数据帧加上一些新数据。解决方案是将所有单个数据帧存储在一个列表中,然后在读取所有文件后连接

frame = []

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)
          .groupby(['Date']).first()
          .add_prefix(f"{filename}-"))
    frame.append(df)

frame = pd.concat(frame, axis=1)

要用一些示例数据说明该概念,请执行以下操作:

df1 = pd.DataFrame(
    {'Date': ['2020-01-01', '2020-01-02', '2020-01-02', '2020-01-03'], 
     'A': [4, 5, 55, 6], 
     'B': [7, 8, 85, 9]}
).set_index('Date')
df2 = pd.DataFrame(
    {'Date': ['2020-01-02', '2020-01-03', '2020-01-04'], 
     'A': [40, 50, 60], 
     'C': [70, 80, 90]}
).set_index('Date')

frame = []

for n, df in enumerate([df1, df2]): #filepath has the rest of the files
    df = (df.groupby(level=['Date']).first()
          .add_prefix(f"{n}-"))
    frame.append(df)

frame = pd.concat(frame, axis=1)

>>> frame
            0-A  0-B   1-A   1-C
2020-01-01  4.0  7.0   NaN   NaN
2020-01-02  5.0  8.0  40.0  70.0
2020-01-03  6.0  9.0  50.0  80.0
2020-01-04  NaN  NaN  60.0  90.0

​

相关问题 更多 >