Python中的Numpy详解-2-访问和删除 ndarray 中的元素及向其中插入元素

本文介绍了如何在Python的Numpy库中操作ndarray,包括通过索引访问元素,正负索引的区别,以及如何删除和添加元素。删除元素使用`numpy.delete`函数,添加元素则使用`numpy.append`。此外,还讲解了如何向ndarray中插入值以及如何堆叠ndarray。
摘要由CSDN通过智能技术生成

访问和删除 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 中的元素。方法是访问要更改的元素,然后使用 =

  • 23
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值