访问和删除 ndarray 中的元素及向其中插入元素
访问和删除:
访问
你已经知道如何创建各种 ndarray,现在将学习 NumPy 使我们如何有效地操纵 ndarray 中的数据。NumPy ndarray 是可变的,意味着 ndarray 中的元素在 ndarray 创建之后可以更改。NumPy ndarray 还可以切片,因此可以通过多种方式拆分 ndarray。例如,我们可以从 ndarray 中获取想要的任何子集。通常,在机器学习中,你需要使用切片拆分数据,例如将数据集拆分为训练集、交叉验证集和测试集
。
我们首先将了解如何通过索引访问
或修改 ndarray 中的元素
。可以在方括号 [ ] 中添加索引来访问元素。在 NumPy 中,你可以使用正索引和负索引
访问 ndarray 中的元素。正索引表示从数组的开头访问元素,负索引表示从数组的末尾访问元素。我们来看看如何访问秩为 1 的 ndarray 中的元素:
# We create a rank 1 ndarray that contains integers from 1 to 5
x = np.array([1, 2, 3, 4, 5])
# We print x
print()
print('x = ', x)
print()
# Let's access some elements with positive indices
print('This is First Element in x:', x[0])
print('This is Second Element in x:', x[1])
print('This is Fifth (Last) Element in x:', x[4])
print()
# Let's access the same elements with negative indices
print('This is First Element in x:', x[-5])
print('This is Second Element in x:', x[-4])
print('This is Fifth (Last) Element in x:', x[-1])
x = [1 2 3 4 5]
This is First Element in x: 1
This is Second Element in x: 2
This is Fifth (Last) Element in x: 5
This is First Element in x: 1
This is Second Element in x: 2
This is Fifth (Last) Element in x: 5
注意,要访问 ndarray 中的第一个元素,我们需要使用索引 0
,而不是 1。此外注意,可以同时使用正索引和负索引访问同一个元素。正如之前提到的,正索引用于从数组的开头访问元素,负索引用于从数组的末尾访问元素。
现在我们看看如何更改秩为 1 的 ndarray 中的元素。方法是访问要更改的元素,然后使用 =
符