我如何检查一个值是否已经出现在Pandasdf列中?

u3r8eeie  于 2022-11-20  发布在  其他
关注(0)|答案(1)|浏览(224)

我有一个股票价格的数据框架...
我希望有一个布尔列,表明价格是否已经达到了一定的阈值在前面的行或没有。
我的输出应该是这样的(假设我的阈值是100):
| 索引|标价|布尔值|
| - -|- -|- -|
| 第0页|九十八|错误|
| 一个|九十九|错误|
| 2个|100.5分|正确|
| 三个|一百零一|正确|
| 四个|九十九|正确|
| 五个|九十八|正确|
我已经设法用下面的代码做到了这一点,但效率不高,而且花费了很多时间:

  1. (df.loc[:, 'price'] > threshold).cumsum().fillna(0).gt(0)

拜托,有什么建议吗?

ee7vknir

ee7vknir1#

使用比较和cummax

  1. threshold = 100
  2. df['bool'] = df['price'].ge(threshold).cummax()

请注意,它可以以相反的方式工作(尽管可能效率较低 *):

  1. threshold = 100
  2. df['bool'] = df['price'].cummax().ge(threshold)

输出量:

  1. index price bool
  2. 0 0 98.0 False
  3. 1 1 99.0 False
  4. 2 2 100.5 True
  5. 3 3 101.0 True
  6. 4 4 99.0 True
  7. 5 5 98.0 True
  • 实际上是在大阵列上:
  1. %%timeit
  2. df['price'].ge(threshold).cummax()
  3. # 193 µs ± 4.96 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  4. %%timeit
  5. df['price'].cummax().ge(threshold)
  6. # 309 µs ± 4.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
计时
  1. # setting up a dummy example with 10M rows
  2. np.random.seed(0)
  3. df = pd.DataFrame({'price': np.random.choice([0,1], p=[0.999,0.001], size=10_000_000)})
  4. threshold = 0.5
  5. ## comparison
  6. %%timeit
  7. df['bool'] = (df.loc[:, 'price'] > threshold).cumsum().fillna(0).gt(0)
  8. # 271 ms ± 28.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  9. %%timeit
  10. df['bool'] = df['price'].ge(threshold).cummax()
  11. # 109 ms ± 5.74 ms per loop (mean ± std. dev. of 7 runs, 10 loops each
  12. %%timeit
  13. df['bool'] = np.maximum.accumulate(df['price'].to_numpy()>threshold)
  14. # 75.8 ms ± 2.86 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
展开查看全部

相关问题