我有以下数据框,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
或者,您可以创建一个新的系列,在其中填充2
s和3
s而其他位置填充nan
s,然后可以对该新系列进行正向填充,这将只给一个包含2
s和3
s的系列(可能nan
在开头的是s )。最后,您可以检查是否3
S IN的Second
有一个前值2
的preceding
列:
# 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] 删除。
我来说两句