python - 切片 numpy 数组

标签 python numpy

this 中的练习教程说:

Generate a 10 x 3 array of random numbers (in range [0,1]). For each row, pick the number closest to 0.5.

Use abs and argsort to find the column j closest for each row.

Use fancy indexing to extract the numbers. (Hint: a[i,j] – the array i must contain the row numbers corresponding to stuff in j.)

所以我做了一切,但我觉得我使用的切片方法(以及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/

相关文章:

Python 数组中数字的总和,忽略特定数字的部分

python - 在 Makefile 的内置 shell 函数中使用 make 变量

python - matplotlib.pyplot 与参数 s 中的 matplotlib.pyplot.scatter 出现问题

python - 如何添加数组元素 (u,v) 的索引 (x,y) 以获得元素数组 (x,y,u,v)?

python - FFT 结果 Matlab VS Numpy (Python) : not the same results

Python MeanShift 内存错误

python - 使用 Python 将代码直接导入脚本?

python - 从 Excel 数据循环到每个键有多个值的字典中

python - 将具有相同列表属性的对象分组

python - 减去两个 Pandas Dataframe