srk*_*kdb 2 python vectorization pandas
我有一部分数据框df是这样的:
| nr | Time | Event |
|----|------|-------|
| 70 | 8 | |
| 70 | 0 | |
| 70 | 0 | |
| 74 | 52 | |
| 74 | 12 | |
| 74 | 0 | |
Run Code Online (Sandbox Code Playgroud)
我想将事件分配到最后一列。默认情况下,第一个条目是1。
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.
Run Code Online (Sandbox Code Playgroud)
如何有效地向量化?我想避免循环。
在定义条件时,您将输出定义为取决于过去的输入。通常,这需要迭代。但是,如果您对输出的看法有所不同,而只是考虑值的变化是(1或0),则可以使用进行矢量化numpy.select。
一般来说:
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())
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |