如何在熊猫数据帧中向量化比较?

时间:2019-05-14 17:05:00

标签: python pandas vectorization

我有一部分数据帧df,如下所示:

| nr | Time | Event |
|----|------|-------|
| 70 | 8    |       |
| 70 | 0    |       |
| 70 | 0    |       |
| 74 | 52   |       |
| 74 | 12   |       |
| 74 | 0    |       |

我想将事件分配到最后一列。默认情况下,第一个条目是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. 

如何有效地向量化?我想避免循环。

2 个答案:

答案 0 :(得分:5)

在定义条件时,您将输出定义为取决于过去的输入。通常,这需要迭代。但是,如果您对输出的看法有所不同,而只是考虑值的变化是(1或0),则可以使用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

答案 1 :(得分:0)

您有三个条件。我注意到,虽然您没有时间== 7的条件?

也就是说,您的三个条件中的两个将1添加到上一个事件。因此,首先使“事件”列等于1,然后更改第三个条件的值。

df['Event'] = 1

   nr  Time  Event
0  70     8      1
1  70     0      1
2  70     0      1
3  74    52      1
4  74    12      1
5  74     0      1

然后过滤其他条件,并将“事件”设置为0

df.loc[(df['Time'] < 7) & (df['nr'] == df['nr'].shift(1)), 'Event'] = 0

  nr  Time  Event
0  70     8      1
1  70     0      0
2  70     0      0
3  74    52      1
4  74    12      1
5  74     0      0

然后cumsum()

df['Event'] = df['Event'].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