我有一个包含日期时间列、条件、此类条件连续发生次数的计数器以及值列的数据框。看起来像:
date condition count Value
01,01,2018 08:00 A 1 9
01,01,2018 08:01 A 2 9
01,01,2018 08:02 A 3 9
01,01,2018 08:03 B 1 9
01,01,2018 08:04 B 2 9
01,01,2018 08:05 B 3 4
01,01,2018 08:06 B 4 9
01,01,2018 08:07 C 1 9
01,01,2018 08:08 C 2 9
01,01,2018 08:09 C 3 9
01,01,2018 08:10 C 4 9
我需要一个错误列,它在 1 和 3 之间的所有行中返回 1 并且条件 = B 时:
-条件= B
-计数 <= 3
-至少一个值 < 5
期望的结果是:
enter code here
date condition count Value error
01,01,2018 08:00 A 1 9 0
01,01,2018 08:01 A 2 9 0
01,01,2018 08:02 A 3 9 0
01,01,2018 08:03 B 1 9 1
01,01,2018 08:04 B 2 9 1
01,01,2018 08:05 B 3 4 1
01,01,2018 08:06 B 4 9 0
01,01,2018 08:07 C 1 9 0
01,01,2018 08:08 C 2 9 0
01,01,2018 08:09 C 3 9 0
01,01,2018 08:10 C 4 9 0
我试过:
df['error']=np.where((df['condition']=='B') & (df['count']<=5) & ((df['Value']).all()>=5), 1, 0)
df['error']=np.where((df['condition']=='B') & (df['count']<=5) & (df.value.apply(lambda x: x<5).any()),0,1)
但它们似乎都不起作用。你能帮助我吗?谢谢:)
最佳答案
试试这个:
df.loc[(df['condition']=='B')&(df['count']<=3),'error']=1
演示(按完整代码执行):
df = your data
df['error']=0
df.loc[(df['condition']=='B')&(df['count']<=3),'error']=1
print(df)
输出:
date condition count Value error
01,01,2018 08:00 A 1 9 0
01,01,2018 08:01 A 2 9 0
01,01,2018 08:02 A 3 9 0
01,01,2018 08:03 B 1 9 1
01,01,2018 08:04 B 2 9 1
01,01,2018 08:05 B 3 4 1
01,01,2018 08:06 B 4 9 0
01,01,2018 08:07 C 1 9 0
01,01,2018 08:08 C 2 9 0
01,01,2018 08:09 C 3 9 0
01,01,2018 08:10 C 4 9 0
现在它符合预期。
关于python - Pandas :检查列的子集中的任何值是否符合条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52870728/