this 中的练习教程说:
Generate a 10 x 3 array of random numbers (in range
[0,1]
). For each row, pick the number closest to0.5
.Use
abs
andargsort
to find the columnj
closest for each row.Use fancy indexing to extract the numbers. (Hint:
a[i,j]
– the arrayi
must contain the row numbers corresponding to stuff inj
.)
所以我做了一切,但我觉得我使用的切片方法(以及b
的初始化)根本不是pythonic:
a = np.random.rand(10,3)
mask = np.argmin(abs(a-0.5), axis = 1)
b = np.ones(mask.size)
for j in range(0,mask.size):
b[j] = a[j,mask[j]]
不使用 for
循环的另一种方法是什么?
最佳答案
import numpy as np
a = np.random.rand(10,3)
b = np.argmin(abs(a - .5), axis=1).choose(a.T)
# a
array([[ 0.97272372, 0.45351387, 0.19105835],
[ 0.27895897, 0.12438789, 0.64857335],
[ 0.05298066, 0.58122882, 0.805319 ],
[ 0.39952727, 0.77728036, 0.65742471],
[ 0.36522802, 0.06938552, 0.6595684 ],
[ 0.9030323 , 0.08965774, 0.01823633],
[ 0.30996923, 0.53400339, 0.87600912],
[ 0.17953532, 0.4888832 , 0.0746074 ],
[ 0.09052476, 0.47397504, 0.30317449],
[ 0.31851577, 0.68135476, 0.38335483]])
# b
array([ 0.45351387, 0.64857335, 0.58122882, 0.39952727, 0.36522802,
0.9030323 , 0.53400339, 0.4888832 , 0.47397504, 0.38335483])
关于python - 切片 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11117868/