文章目录
一、数组的索引、切片
- 索引:通过下标访问数组元素
- 切片: 用:来进行切片
- 本质都是通过不同轴的元素下标来进行定位
二维数组索引方式: - 举例:获取第一个股票的前3个交易日的涨跌幅数据
# 二维的数组,两个维度
stock_change[0, 0:3]
返回结果:
array([-0.03862668, -1.46128096, -0.75596237])
- 三维数组索引方式:
# 三维
a1 = np.array([ [[1,2,3],[4,5,6]], [[12,3,34],[5,6,7]]])
# 返回结果
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[12, 3, 34],
[ 5, 6, 7]]])
# 索引、切片
>>> a1[0, 0, 1] # 输出: 2
二、形状修改
2.1 ndarray.reshape(shape, order)
- 返回一个具有相同数据域,但shape不一样的视图
# 在转换形状的时候,一定要注意数组的元素匹配
stock_change.reshape([5, 4])
stock_change.reshape([-1,10]) # 数组的形状被修改为: (2, 10), -1: 表示通过待计算
你有没有这个困惑:在 reshape 之后,数据在各个轴上是如何重新分配的?
搞清楚 ndarray 的数据在内存里的存放方式,以及各个维度的访问方式,reshape 困惑就迎刃而解了。
心法: ndarray 的数据在内存里以一维线性存放,reshape 之后,数据并没有移动,只是访问方式变了而已。
数据优先填充 X 轴向,其次 Y 轴,其次 Z 轴 。。。
2.2 ndarray.resize(new_shape)
- 修改数组本身的形状(需要保持元素个数前后相同)
stock_change.resize([5, 4])
# 查看修改后结果
stock_change.shape
(5, 4)
2.3 ndarray.T
- 数组的转置
- 将数组的行、列进行互换
stock_change.T.shape
(4, 5)
三、类型修改
- ndarray.astype(type)
- 返回修改了类型之后的数组
stock_change.astype(np.int32)
四、数组的去重
- np.unique()
temp = np.array([[1, 2, 3, 4],[3, 4, 5, 6]])
>>> np.unique(temp)
array([1, 2, 3, 4, 5, 6])