np.where在第一栏检查True,然后在另一栏检查

苏拉杰

我有以下数据框,np.where条件为:

df=pd.DataFrame(data = {'First':[1,2,4,6,2,7,8,9],'Second':[4,6,7,3,1,3,9,3]})
df['First_check']=np.where(df['First']==2,'T','F')

df

   First    Second  First_check
0       1       4       F
1       2       6       T
2       4       7       F
3       6       3       F
4       2       1       T
5       7       3       F
6       8       9       F
7       9       3       F

现在,我想检查,df['Second']==3但仅在之后,df['First_check']=='T'我只想第一次出现病情。

以下是我想要的输出:

   First    Second  First_check Second_check
0       1       4       F           F
1       2       6       T           F
2       4       7       F           F
3       6       3       F           T
4       2       1       T           F
5       7       3       F           T
6       8       9       F           F
7       9       3       F           F

编辑:我想df['Second']==3成为True,但第一df['First_check']=='T'应该成为True,那么它可能不在同一行。说,row 2 df['First_check']=T那么它应该检查下一行2,3,4 ...,因为df['Second']==3它与row 4th

智慧

或者,您可以创建一个新的系列,在其中填充2s和3s而其他位置填充nans,然后可以对该新系列进行正向填充,这将只给一个包含2s和3s的系列(可能nan在开头的s )。最后,您可以检查是否3S IN的Second有一个前值2preceding列:

# firstly merge two and three into a single Series and do a forward fill
preceding = df.First.shift(-1).where(
    df.First.shift(-1).eq(2), 
    df.Second.where(df.Second.eq(3))
).ffill()

preceding
#0    2.0
#1    2.0
#2    2.0
#3    2.0
#4    2.0
#5    3.0
#6    3.0
#7    3.0
#Name: First, dtype: float64

# after the forward fill if a 3 is preceded by a 2, then it should be True
df.Second.eq(3) & preceding.shift().eq(2)
#0    False
#1    False
#2    False
#3     True
#4    False
#5     True
#6    False
#7    False
#Name: First, dtype: bool

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章