需要帮助有条件地向列表矢量化



我需要帮助在python中向量化下面的代码。电流循环太慢,不能满足我的需要。

如果a是您的列表

[-1.5,-1,-1,0,0,-1,0,1.5,1,1,1,0,0,0,0,1,0,0,10,1,0,1.5,1,1,00,0,0,0,-1.5…]

以及我们在当前代码之后获得的期望输出如下:[-1,-1,-1,0,0,0,1,1,1,0,0,0,00,0,0,0,0,1,10,1,1,1,1,10,1,0,0,0,-1…]

for index, item in enumerate(a): 
if item == 1.5:
a[index] = 1
elif item == -1.5:
a[index] = -1
elif a[index] == 0:
a[index] = 0
elif (a[index] == 1 or a[index] == -1) and a[index-1] ==0:
a[index] = 0
else:
a[index] = a[index-1]

谢谢!

正如@Bart所建议的,使用numpy可以非常容易地对至少前三个操作进行矢量化。最后一种情况有点棘手,因为你需要知道前三种情况在哪里失败。您还需要小心,因为如果在适当的位置进行计算,早期的更改可能会影响后期的条件(即,将一些值指定为1,然后稍后检查是否等于1的值(。总而言之,你可以做以下事情:

a = np.array(a)
cond1 = a == 1.5
cond2 = a == -1.5
cond3 = ((a == 1) | (a == -1))[1:] & (a[:-1] == 0)
cond4 = ~(cond1[1:] | cond2[1:] | cond3)
a[cond1] = 1
a[cond2] = -1
a[1:][cond3] = 0
a[1:][cond4] = a[1:][cond4]

您可以使用pandas:

import pandas as pd
l = [-1.5,-1,-1,0,0,-1,0,1.5,1,1,1,1,0,0,0,0,1,0,1,0,1.5,1,1,1,1,0,0,0,0,-1.5]
s  = pd.Series(l)
cond1 = (s == 1.5)
cond2 = (s == -1.5)
cond3 = (s == 0)
cond4 = ((s == 1) | (s ==  -1)) & (s.shift() == 0)
out = pd.Series(pd.np.select([cond1, cond2, cond3, cond4],[1, -1, 0 ,0], pd.np.nan)).ffill()
out.tolist()

输出:

[-1.0,
-1.0,
-1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
-1.0]

注意:这是使用Numpy方法np.select进行if-then-else的矢量化方式,该方法通过使用pd.np.select的pandas导入进行访问。默认值为np.nan,在默认情况下,它允许前向填充获取前一行的值。

最新更新