python - 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 矢量化有一点看法,但我不确定这是否是一个合适的解决方法。
可以在此处看到基于递增、递减和恒定值的模式
解决方案
使用Series.gt
和来创建布尔掩码,Series.lt
然后使用这些掩码过滤/拆分相应类别中的数据框,并且:Series.eq
Series.shift
m1
m2
m3
increasing
decreasing
constant
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
推荐阅读
- css - 关闭时模态上的css关键帧动画
- vue.js - Vue - 试图避免改变道具,但没有成功
- c - 如何通过钩子 sys_exit_group 和 sys_kill 使进程无法退出
- c - For循环无法正常工作以获取c中数组中的输入
- java - Java - Selenium - 超出页面视图的 Div 元素即使在滚动到视图后也不会加载
- java - 杰克逊 xmlmapper 用于地图
, 对特定标签做出反应 - c++ - bits/stdtr1c++.h 和 bits/std1c++.h 头文件有什么区别?
- swift - 在 Swift 中将日期格式化为 sql 日期格式
- postgresql - DB的大小和/var/lib/postgresql/data的大小有什么关系
- java - 读取 CSV 并将内容转换为 ArrayList