gpt4 book ai didi

python Pandas : Search rows with consecutive condition

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:41 24 4
gpt4 key购买 nike

我有一个如下所示的数据框:

Text  Label 
a NaN
b NaN
c NaN
1 NaN
2 NaN
b NaN
c NaN
a NaN
b NaN
c NaN

每当模式“a,b,c”向下出现时,我想将该部分标记为字符串,例如“Check”。最终数据框应如下所示:

Text  Label 
a Check
b Check
c Check
1 NaN
2 NaN
b NaN
c NaN
a Check
b Check
c Check

执行此操作的最佳方法是什么。谢谢 =)

最佳答案

这是一个利用广播的基于 NumPy 的方法:

import numpy as np

w = df.Text.cumsum().str[-3:].eq('abc') # inefficient for large dfs
m = (w[w].index.values[:,None] + np.arange(-2,1)).ravel()
df.loc[m, 'Label'] = 'Check'

Text Label
0 a Check
1 b Check
2 c Check
3 1 NaN
4 2 NaN
5 b NaN
6 c NaN
7 a Check
8 b Check
9 c Check

关于 python Pandas : Search rows with consecutive condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56540014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com