python - Numpy:作为 Matlab 的赋值和索引

标签 python numpy indexing

有时只用一个索引分配数组很有用。在 Matlab 中,这很简单:

M = zeros(4);
M(1:5:end) = 1
M =

   1   0   0   0
   0   1   0   0
   0   0   1   0
   0   0   0   1

有没有办法在 Numpy 中做到这一点?首先,我想展平数组,但该操作不会保留引用,因为它会生成一个副本。我尝试使用 ix_,但无法使用相对简单的语法来完成。

最佳答案

你可以试试 numpy.ndarray.flat ,它表示可用于读取和写入数组的迭代器。

>>> M = zeros((4,4))
>>> M.flat[::5] = 1
>>> print(M)
array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.]])

请注意,在 numpy 中,切片语法是 [start:stop_exclusive:step],而不是 Matlab 的 (start:step:stop_inclusive)。

根据 sebergs 评论,指出 Matlab 以列为主存储矩阵可能很重要,而 numpy 数组默认情况下以行为主。

>>> M = zeros((4,4))
>>> M.flat[:4] = 1
>>> print(M)
array([[ 1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

要在展平数组上获得类似 Matlab 的索引,您需要展平转置数组:

>>> M = zeros((4,4))
>>> M.T.flat[:4] = 1
>>> print(M)
array([[ 1.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.]])

关于python - Numpy:作为 Matlab 的赋值和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20688881/

相关文章:

python - 我得到一个 AttributeError : module 'collections' has no attribute 'Iterable' when I try to install libraries using PIP

python - 错误 : random_sample() takes at most 1 positional argument (2 given)

indexing - Google 网站管理员工具网站未编入索引

Java 数组索引

python - 使用文件系统编码对 unicode 路径进行编码会破坏它

python - 有没有更有效的方法从另一个数组生成一个数组,规则有点复杂?

python - 将 SKLearn 癌症数据集加载到 Pandas DataFrame 中

sql-server - SQL Server : ~2000 Heap Tables all using GUID Uniqueidentifier - Possible Clustered Indexing?

python - python中的URL编码

python - 如何在不使用 for 循环的情况下向量化这两个 numpy 运算?