【发布时间】:2019-12-31 17:34:36
【问题描述】:
我有一个如下所示的数据框
df = pd.DataFrame({
'subject_id' :[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
'day':[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
'PEEP' :[7,5,10,10,11,11,14,14,17,17,21,21,23,23,25,25,22,20,26,26,5,7,8,8,9,9,13,13,15,15,12,12,15,15,19,19,19,22,22,15]
})
df['fake_flag'] = ''
在此操作中,我正在执行如下代码所示的操作。此代码工作正常并产生预期的输出,但我不能将这种方法用于真实数据集,因为它有超过百万条记录。
t1 = df['PEEP']
for i in t1.index:
if i >=2:
print("current value is ", t1[i])
print("preceding 1st (n-1) ", t1[i-1])
print("preceding 2nd (n-2) ", t1[i-2])
if (t1[i-1] == t1[i-2] or t1[i-2] >= t1[i-1]):
r1_output = t1[i-2] # we get the max of these two values (t1[i-2]), it doesn't matter when it's constant(t1[i-2] or t1[i-1]) will have the same value anyway
print("rule 1 output is ", r1_output)
if t1[i] >= r1_output + 3:
print("found a value for rule 2", t1[i])
print("check for next value is same as current value", t1[i+1])
if (t1[i]==t1[i+1]):
print("fake flag is being set")
df['fake_flag'][i] = 'fake_vac'
但是,我无法将其应用于真实数据,因为它有超过一百万条记录。我正在学习 Python,你能帮我理解如何在 Python 中对我的代码进行矢量化吗?
你可以参考这个帖子related post来理解逻辑。因为我的逻辑是正确的,所以我创建了这篇文章主要是为了寻求帮助来矢量化和固定我的代码
我希望我的输出如下所示
subject_id = 1
subject_id = 2
有没有什么高效优雅的方法来固定我对一百万条记录数据集的代码操作
【问题讨论】:
-
t1是否与df相同? -
更新了帖子
-
如果您提供输出 df 文本描述您正在尝试做的事情的视图会更好
-
更新了帖子@AkashKumar
-
在
5th列中给出'fake VAC'值的逻辑是什么?我觉得numpy.where()可以用在这里。
标签: python python-3.x pandas vectorization pandas-groupby