假设我有一个如下所示的数据帧:
dftrial = pd.DataFrame({'col 1': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'],
'col 2': [1, -1, -2, -3, 2, -1, 1, 5, 6, -2, -2, -2, -2, 1]})
dftrial
我想创建一个新的数据框,用于标识col 2
为正的位置,然后将该行以及该行下方的下一个x行(在本例中,仅下一行),然后删除重复项
我可以使用iterrows
来做这样的事情,如下所示
storage = []
for index, row in dftrial.iterrows():
if row['col 2'] > 0:
savethis = dftrial[index : index + 2]
storage.append(savethis)
result = pd.concat(storage)
result.drop_duplicates(inplace = True)
display(result)
这将导致我想要的表格:
然而,我在一个有数十万行的数据帧上运行这段代码。按定义运行iterrows
会遍历每一行,这会降低此过程的速度。有没有更快的方法来运行此代码?我知道有一些现有页面提供了iTerrow的替代方案,但它们似乎都没有解释我如何使用它来选择它下面的行
我得到的最接近的方法是使用lambda
函数,如下所示,但该函数只接受col 2大于零的行,不包括以下行。我一直在努力使行的索引正确,任何帮助都将不胜感激
dftrial[dftrial.apply(lambda x: x['col 2'] > 0, axis = 1)]
要生成与描述不完全相同的示例,请执行以下操作:
如果我们严格按照您的描述(“下一列下一列两列”),那么:
解释
当然,关键是首先确定
col 2
为正的行:然后我们使用
rolling().max()
将该真理“出血”到下两行(不幸的是,Rolling
没有.any()
,否则我们将使用它而不是.max() > 0
):然后,只需选择带有该遮罩的行
相关问题 更多 >
编程相关推荐