有没有办法做到以下几点
import numpy as np
x = np.arange(10)
x[2:7] = 1
在一行中?有点像
x = np.arange(10)[2:7] = 1
最佳答案
使用 masking
和 np.in1d
的单行代码和 np.where
用于分配值 -
np.where(np.in1d(range(10),range(2,7)), 1, range(10))
sample 运行-
In [28]: np.where(np.in1d(range(10),range(2,7)), 1, range(10))
Out[28]: array([0, 1, 1, 1, 1, 1, 1, 7, 8, 9])
逐步运行-
获取要分配新值的掩码:
In [44]: np.in1d(range(10),range(2,7))
Out[44]: array([False, False, True, True, True, True, \
True, False, False, False], dtype=bool)
使用掩码和 np.where
在新值 (=1)
和最初定义的值 - range(10)
之间进行选择:
In [45]: np.where(np.in1d(range(10),range(2,7)), 1, range(10))
Out[45]: array([0, 1, 1, 1, 1, 1, 1, 7, 8, 9])
因此,总而言之,语法基本上是 -
np.where(np.in1d(range(10),range(2,7)), 1, range(10))
^ ^ ^ ^
(1) (2) (3) <--(4)-->
(1)要定义的数组长度。
(2) 切片限制。
(3) 作为第二步分配的新值。
(4) 在定义数组时初始化为数组的值。
这是另一个示例用法 -
In [41]: np.where(np.in1d(range(9),range(2,7)), 99, range(10,19))
Out[41]: array([10, 11, 99, 99, 99, 99, 99, 17, 18])
重现它的原始样式代码是 -
x = np.arange(10,19)
x[2:7] = 99
关于python - 定义 Numpy 数组并在单行中赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41463311/