The exercise in this tutorial says:
Generate a 10 x 3 array of random numbers (in range
[0,1]). For each row, pick the number closest to0.5.Use
absandargsortto find the columnjclosest for each row.Use fancy indexing to extract the numbers. (Hint:
a[i,j]– the arrayimust contain the row numbers corresponding to stuff inj.)
So I did everything, but I feel the slicing method I used (and the initialisation of b) is not pythonic at all:
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]]
What is the other way of doing this without using the for loop?