似乎是个不错的设置使用np.where
基础上,做面膜的艇员选拔操作/二进制输入数据 -
C = np.where(v[:,None],B,A)
即v[:,None]
部分基本上延伸到v
broadcastable形状A
和B
允许broadcasting
让艇员选拔沿相应的轴的工作,axis=0
在这种情况下为两个2D
阵列。
采样运行 -
In [58]: A
Out[58]:
array([[82, 78, 57],
[14, 97, 32],
[72, 11, 49],
[98, 34, 41],
[89, 71, 52],
[34, 51, 55],
[26, 92, 59]])
In [59]: B
Out[59]:
array([[55, 67, 50],
[49, 64, 21],
[34, 18, 72],
[24, 61, 65],
[56, 59, 23],
[44, 77, 13],
[56, 55, 58]])
In [62]: v
Out[62]: array([1, 0, 0, 0, 0, 1, 1])
In [63]: np.where(v[:,None],B,A)
Out[63]:
array([[55, 67, 50],
[14, 97, 32],
[72, 11, 49],
[98, 34, 41],
[89, 71, 52],
[44, 77, 13],
[56, 55, 58]])
如果v
并不严格包括0s
和1s
只,用v[:,None]==1
与np.where
第一个参数。
另一种方法是用boolean-indexing
-
C = A.copy()
mask = v==1
C[mask] = B[mask]
注:如果v
已经是一个布尔数组,跳过对1
的掩模制作的比较。
运行测试 -
In [77]: A = np.random.randint(11,99,(10000,3))
In [78]: B = np.random.randint(11,99,(10000,3))
In [79]: v = np.random.rand(A.shape[0])>0.5
In [82]: def choose_rows_copy(A, B, v):
...: C = A.copy()
...: C[v] = B[v]
...: return C
...:
In [83]: %timeit np.where(v[:,None],B,A)
10000 loops, best of 3: 107 µs per loop
In [84]: %timeit choose_rows_copy(A, B, v)
1000 loops, best of 3: 226 µs per loop
你能提供A和B的例子,看你想要什么C样的呢? –
我添加了一个示例 – user3726947