首页 > 解决方案 > Python中子数据帧中数据帧拆分的优化运行时间

问题描述

我确实有一个 pandas DF (df_main),我尝试将其拆分为不同的子集。数据集如下所示:

a b c d e f

1 1 1 2 1 2   1.

2 3 2 1 2 1   2.

3 1 3 1 3 1   3.

3 2 1 3 4 1   4.

3 1 3 4 2 1   5.

2 1 2 3 4 2   6.

1 2 3 4 5 3   7.

我想df根据列 a的元素将完整的元素拆分为 3 个子集。

子集 1:增加 的值col(a),因此 1.、2.、3。

子集 2:值col(a)保持不变,因此 3.、4.、5。

col (a)子集 3: so 5., 6., 7的递减值。

我的代码现在看起来像这样:

df1_new = pd.DataFrame(columns=['a', 'b', 'c', 'd', 'e', 'f'])
df2_new = pd.DataFrame(columns=['a', 'b', 'c', 'd', 'e', 'f'])
df3_new = pd.DataFrame(columns=['a', 'b', 'c', 'd', 'e', 'f'])

for j in range(len(df_main['a'])):
    if df_main['a'][j] == df_main['a'][j + 1]:
        df1_new = df1_new.append(df_main.iloc[j])
    if df_main['a'][j] > df_main['a'][j + 1]:
        df2_new = df2_new.append(df_main.iloc[j])
    if df_main['a'][j] < df_main['a'][j + 1]:
        df3_new = df3_new.append(df_main.iloc[j])

由于 df_main 的长度为 1 353 419 行,它需要(atm)大约 15 小时才能完成一次运行。

是否有任何选项可以优化它运行 df 并拆分它所需的时间?

我对 numpy 矢量化有一点看法,但我不确定这是否是一个合适的解决方法。

可以在此处看到基于递增、递减和恒定值的模式

在此处输入图像描述

标签: pythonpandasdataframeoptimization

解决方案


使用Series.gt和来创建布尔掩码,Series.lt然后使用这些掩码过滤/拆分相应类别中的数据框,并且:Series.eqSeries.shiftm1m2m3increasingdecreasingconstant

s1, s2 = df['a'].shift(), df['a'].shift(-1)

m1 = df['a'].gt(s1) | df['a'].lt(s2)
m2 = df['a'].lt(s1) | df['a'].gt(s2)
m3 = df['a'].eq(s1) | df['a'].eq(s2)

incr, decr, const = df[m1], df[m2], df[m3]

结果:

print(incr)
   a  b  c  d  e  f  g
0  1  1  1  2  1  2  1
1  2  3  2  1  2  1  2
2  3  1  3  1  3  1  2

print(decr)
   a  b  c  d  e  f  g
4  3  1  3  4  2  1  4
5  2  1  2  3  4  2  1
6  1  2  3  4  5  3  1

print(const)
   a  b  c  d  e  f  g
2  3  1  3  1  3  1  2
3  3  2  1  3  4  1  3
4  3  1  3  4  2  1  4

推荐阅读