Skip to main content
 首页 » 编程设计

python之如何提高 Pandas 中concat的速度

2024年12月31日9落叶无声

我想通过定期复制行来扩展我的数据框。

import pandas as pd  
import numpy as np  
def expandData(data, timeStep=2, sampleLen= 5): 
    dataEp = pd.DataFrame() 
    for epoch in range(int(len(data)/sampleLen)): 
        dataSample = data.iloc[epoch*sampleLen:(epoch+1)*sampleLen, :] 
        for num in range(int(sampleLen-timeStep +1)): 
            tempDf = dataSample.iloc[num:timeStep+num,:] 
            dataEp = pd.concat([dataEp, tempDf],axis= 0) 
    return dataEp 
 
df = pd.DataFrame({'a':list(np.arange(5))+list(np.arange(15,20)), 
'other':list(np.arange(100,110))}) 
dfEp = expandData(df, 3, 5) 

输出:

df 
     a  other 
0   0    100 
1   1    101 
2   2    102 
3   3    103 
4   4    104 
5  15    105 
6  16    106 
7  17    107 
8  18    108 
9  19    109 
 
dfEp 
     a  other 
0   0    100 
1   1    101 
2   2    102 
1   1    101 
2   2    102 
3   3    103 
2   2    102 
3   3    103 
4   4    104 
5  15    105 
6  16    106 
7  17    107 
6  16    106 
7  17    107 
8  18    108 
7  17    107 
8  18    108 
9  19    109 

预期:

我希望有一种更好的方法来实现它并具有良好的性能,如果数据帧具有较大的行大小,例如 40,000 行,我的代码将运行大约 20 分钟。

编辑:

实际上,我希望重复一个大小为 timeStep 的小序列。我已将 expandData(df, 2, 5) 更改为 expandData(df, 3, 5)。

请您参考如下方法:

如果您的 a 值间隔均匀,您可以测试系列中的中断,然后根据 this answer 复制每个连续系列中的行:

df = pd.DataFrame({'a':list(np.arange(5))+list(np.arange(15,20)), 
'other':list(np.arange(100,110))}) 
#equally spaced rows have value zero, start/stop rows not 
df["start/stop"] = df.a.diff().shift(-1) - df.a.diff() 
#repeat rows with value zero in the new column 
repeat = [2 if val == 0 else 1 for val in df["start/stop"]] 
df = df.loc[np.repeat(df.index.values, repeat)] 
print(df) 

示例输出:

    a  other  start/stop 
0   0    100         NaN 
1   1    101         0.0 
1   1    101         0.0 
2   2    102         0.0 
2   2    102         0.0 
3   3    103         0.0 
3   3    103         0.0 
4   4    104        10.0 
5  15    105       -10.0 
6  16    106         0.0 
6  16    106         0.0 
7  17    107         0.0 
7  17    107         0.0 
8  18    108         0.0 
8  18    108         0.0 
9  19    109         NaN 

如果只是关于epoch的长度(你没有明确规定规则),那就更简单了:

df = pd.DataFrame({'a':list(np.arange(5))+list(np.arange(15,20)), 
'other':list(np.arange(100,110))}) 
 
sampleLen = 5 
repeat = np.repeat([2], sampleLen) 
repeat[0] = repeat[-1] = 1 
repeat = np.tile(repeat, len(df)//sampleLen) 
 
df = df.loc[np.repeat(df.index.values, repeat)]