如何矢量化 pandas 数据框中的比较? [英] How to vectorize comparison in pandas dataframe?
本文介绍了如何矢量化 pandas 数据框中的比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一部分数据帧 df
像这样:
I have a part of dataframe df
like this:
| nr | Time | Event |
|----|------|-------|
| 70 | 8 | |
| 70 | 0 | |
| 70 | 0 | |
| 74 | 52 | |
| 74 | 12 | |
| 74 | 0 | |
我想将事件分配到最后一列.第一个条目默认为 1.
I want to assign events to the last column. The first entry is 1 by default.
If Time[i] < 7 and nr[i] != nr[i-1], then Event[i]=Event[i-1]+1.
If Time[i] < 7 and nr[i] = nr[i-1], then Event[i]=Event[i-1]
If Time[i] > 7 then Event[i]=Event[i-1]+1.
我如何有效地矢量化它?我想避免循环.
How do I effectively vectorize this? I want to avoid loops.
推荐答案
在您的条件定义中,您将输出定义为依赖于过去的输入.通常这需要迭代.但是,如果您对输出的看法有点不同,而只是考虑值的 变化 是什么(1 或 0),则可以使用 numpy.select
对其进行矢量化.
In your definition of your conditions, you define the outputs as being dependent on past inputs. Usually this requires iteration. However, if you think about your outputs a bit differently, and instead just consider what the change in value is (1 or 0), you can vectorize this with numpy.select
.
一般来说:
- 如果满足第一个条件,则将系列增加 1
- 如果满足第二个条件,则保持系列不变
- 否则,将系列增加 1
t = df.Time.lt(7)
n = df.nr.ne(df.nr.shift())
o = np.select([t & n, t & ~n], [1, 0], 1)
o[0] = 1 # You say first value is 1
df.assign(Event=o.cumsum())
nr Time Event
0 70 8 1
1 70 0 1
2 70 0 1
3 74 52 2
4 74 12 3
5 74 0 3
这篇关于如何矢量化 pandas 数据框中的比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文