python - 定义 Numpy 数组并在单行中赋值

标签 python arrays numpy

有没有办法做到以下几点

import numpy as np
x = np.arange(10)
x[2:7] = 1

在一行中?有点像

x = np.arange(10)[2:7] = 1

最佳答案

使用 maskingnp.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/

相关文章:

python - Concurrent.futures : what are the use cases for map() vs. 提交()?

python - 为什么 asyncio.Future 与 concurrent.futures.Future 不兼容?

python - 无需额外检查即可堆叠 Numpy 数组

c - 取消引用包含对象(数组的数组)地址的出界指针

c - 匹配两个数组的有效方法

python - 在python中没有负值的情况下进行插值

python - 多维 numpy 数组 __eq__

python - 使用 Python 3 和 Beautiful Soup 4 删除 HTML 标签并将抓取的数据保存到 CSV 文件

python - 使用 while 循环递增数组中的值,直到所有值 => 100

Python 相当于 Ruby 的 .select