Python:关于 "numpy.ndarray"的两个问题

标签 python arrays numpy

我创建了一个带有值的 numpy.ndarray

将 numpy 导入为 np 从 numpy 导入非零

data = np.zeros((5, 5))
data
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

我希望用 1 更改一些值

data[0,0] = 1
data[4,4] = 1

data
array([[ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.]])

如果我使用负值将 0 更改为 5

data[-5,-5] = 5
data[-4,-4] = 5

>>> data
array([[ 5.,  0.,  0.,  0.,  0.],
       [ 0.,  5.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

1-我不明白为什么我没有错误消息

>>> data[10,10] = 5
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
IndexError: index (10) out of range (0<=index<5) in dimension 0

2-不清楚为什么 data[-5,-5] = 5 和 data[-4,-4] = 5 值 5 被插入到位置 0,0 和 1,1

最佳答案

来自the documentation :

Negative indices are interpreted as counting from the end of the array

这是标准的 Python 索引行为(用于 Python 列表等)。

关于Python:关于 "numpy.ndarray"的两个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14946470/

相关文章:

python - matplotlib plt 中基于数据某些属性的多色图

Python 递归 : nested list from flat list

python - 斐波那契和非斐波那契编码

python - 如何从 Python 执行 Common Lisp 代码

java数组,执行正数和负数

python - 创建随机值并将其传递给具有硬边界的 Pandas 数据帧

python - Django FileField 在上传后移动文件

arrays - C如何将.txt文件的内容放入二维数组

Java多维数组程序问题

python - 比较 numpy 数组中的以下两个值