Day03:Numpy数组的操作

Numpy数组操作

先补充一下数组的迭代,利用apply_along_axis(func, axis, arr)对数组进行操作,func是自定义函数,axis表示函数func对arr是作用于行还是列。

下面开始今天的内容

更改形状

numpy.ndarray.shape表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即ndim属性(秩(数组的维数)),一般的数组秩为2。
这里介绍一下数组的秩:在Numpy中,每一个线性的数组称为是一个轴(axes),秩其实是描述轴的数量。举个栗子哈,二维数组相当于是两个一维数组,一维数组里的每一个元素又是一个个一维数组。所以一维数组就是Numpy中的轴(axes),第一个轴相当于是底层数组,第二个轴是底层数组里的数组。而轴的数量——秩,就是数组的维数。

  1. 通过修改shape属性来改变数组的形状
import numpy as np
x = np.array([1,2,3,4,5,6,7,8,9])
print(x.shape) 
x.shape = [3, 3]#这里我试了一下其他的数,发现这两个数字是有规律的,只能是数组元素个数的公因数
print(x)
#(9,)
#[[1 2 3]
#[4 5 6]
#[7 8 9]]
  1. numpy.ndarray.flat将数组转换为一维的迭代器,然后用for访问数组每一个元素。
import numpy as np
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = x.flat
print(y)
#<numpy.flatiter object at 0x000002C394A53C20>将二维数组转换为一维迭代
for i in y:
    print(i, end=' ')
y[::3,] = 0
print(end='\n')
print(x)

#11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 
#[[[ 0 12 13  0 15]
#[16  0 18 19  0]
#[21 22  0 24 25]
#[ 0 27 28  0 30]
#[31  0 33 34  0]]

注意flat和flatten的区别,详情如下
flat和flatten的区别

3.numpy.ndarray.flatten([order=‘C’]) 将数组的副本转换为一维数组,并返回。
a.order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘k’ – 元素在内存中的出现顺序。
b.order:{'C / F,'A,K},可选使用此索引顺序读取a的元素。'C’意味着以行大的C风格顺序对元素进行索引,最后一个轴索引会更改F 表示以列大的F样式顺序索引元素,其中第一个索引变化最快,最后一个索引变化最快。请注意,'C’和’F’选项不考虑基础数组的内存布局,仅引用轴索引的顺序.A’表示如果a为F,则以类似F的索引顺序读取元素在内存中连续,否则类似C的顺序。“ K” 表示按照步序在内存中的顺序读取元素,但步幅为负时反转数据除外。默认情况下,使用C顺序。

import numpy as np
x=np.array([[2,3,2],[4,5,4],[2,5,6]])
y=x.flatten()
print(y)
y=x.flatten(order='F')
print(y)
y=x.flatten(order='K')
print(y)
y=x.flatten(order='C')
print(y)
y=x.flatten(order='A')
print(y)
#[2 3 2 4 5 4 2 5 6]
#[2 4 2 3 5 5 2 4 6]
#[2 3 2 4 5 4 2 5 6]
#[2 3 2 4 5 4 2 5 6]
#[2 3 2 4 5 4 2 5 6]

4.numpy.ravel(a,order=‘C’) ,ravel()返回的是视图。

import numpy as np
x=np.array([[2,3,2],[4,5,4],[2,5,6]])
y = np.ravel(x, order='F')#order='F'是拷贝
print(y)
#[2 4 2 3 5 5 2 4 6]

5.numpy.reshape(a, newshape[, order=‘C’])在不更改数据的情况下为数组赋予新的形状。reshape() 函数,当参数 newshape = [rows,-1] 时,将根据行数自动确定列数(改变数组的形状,但原始数据不发生变化,reshape()函数中的参数需要满足乘积等于数组中数据总数)。
shape和reshape的区别

import numpy as np
x = np.arange(12)
y = np.reshape(x, [3, 4])#这里的这两个数据也是公因数
print(y.dtype)
# int32
print(y)
#[[ 0  1  2  3]
#[ 4  5  6  7]
#[ 8  9 10 11]]
y = np.reshape(x,[-1,3])#(-1根据列数自动确定行数)
print(y)
# [[ 0  1  2]
# [ 3  4  5]
# [ 6  7  8]
# [ 9 10 11]]
y[0, 1] = 10
print(x)
# [ 0 10 2 3 4 5 6 7 8 9 10 11](改变x去reshape后y中的值,x对应元素也改变)

6.reshape() 函数当参数 newshape = -1 时,表示将数组降为一维。

import numpy as np
x = np.random.randint(12, size=[3, 3, 2])
print(x)
y = np.reshape(x, -1)
print(y)
#[[[ 0  0  1]
#[11  9  6]
#[ 0  9  7]]

#[[ 1  3  8]
#[ 1  5  5]
#[ 9 10  9]]

#[[ 5  3  4]
#[ 5  9  9]
#[ 1 11  0]]]
#[ 0  0  1 11  9  6  0  9  7  1  3  8  1  5  5  9 10  9  5  3  4  5  9  9 1 11  0]

数组的转置

  • numpy.transpose(a, axes=None)计算数组的维数
  • numpy.ndarray.T与self.transpose()相同但如果它的秩小于2,直接返回原矩阵。
import numpy as np
x = np.random.rand(3, 3) * 5
x = np.around(x, 2)
print(x)
y=x.T
print('\n')
print(y)
y=np.transpose(x)
print('\n')
print(y)
#[[4.8  3.13 4.64]
#[2.98 2.76 4.33]
#[4.06 3.76 1.73]]

#[[4.8  2.98 4.06]
#[3.13 2.76 3.76]
#[4.64 4.33 1.73]]

#[[4.8  2.98 4.06]
#[3.13 2.76 3.76]
#[4.64 4.33 1.73]]

更改维度

  1. 使用 newaxis 参数来增加一个维度。
    numpy.newaxis=None,None 的别名,对索引数组很有用。
    很多工具包在进行计算时都会先判断输入数据的维度是否满足要求,如果输入数据达不到指定的维度时,可以使用 newaxis 参数来增加一个维度。
import numpy as np
x = np.array([1,2,3,4,5])
print(x.shape) 
print(x) 
y = x[np.newaxis, :]
print(y.shape)  
print(y) 
y = x[:, np.newaxis]
print(y.shape)
print(y)
#(5,)
#[1 2 3 4 5]

#(1, 5)
#[[1 2 3 4 5]]

#(5, 1)
#[[1]
#[2]
#[3]
#[4]
#[5]]

2.numpy.squeeze(a, axis=None)从数组的形状中删除单维度条目,即把shape中为1的维度去掉。
a.a 表示输入的数组;从数组的形状中删除单维度条目,即把shape中为1的维度去掉。
b.axis 用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;在机器学习和深度学习中,通常算法的结果是可以表示向量的数组(即包含两对或以上的方括号形式[[]]),如果直接利用这个数组进行画图 可能显示界面为空(见后面的示例)。我们可以利用 squeeze() 函数将表示向量的数组转换为秩为1的数组,这样利用 matplotlib 库函数画图时,就可以正常的显示结果了。

import numpy as np
x = np.array([[[5], [1], [3]]])
print(y)
y = np.squeeze(x)
print(y.shape) 
print(y) 
y = np.squeeze(x, axis=0)#秩
print(y.shape) 
print(y)
#[[5]
#[1]
#[3]]
#(3,)
#[5 1 3]
#(3, 1)
#[[5]
#[1]
#[3]]
import matplotlib.pyplot as plt
x = np.array([[2, 5, 1, 3, 6]])
print(x.shape) 
plt.plot(x)
plt.show()

输出后的数据

数组的拼接与组合

  1. numpy.concatenate((a1, a2, …), axis=0, out=None)沿着轴连接数组数据
    连接沿现有轴的数组序列
import numpy as np
x = np.array([2, 2, 3])
y = np.array([1, 2, 1])
z = np.concatenate([x, y])
print(z)
z = np.concatenate([x, y], axis=0)#这(原来x,y都是一维的,拼接后的结果也是一维的,所以秩为0)。
print(z)
#[2 2 3 1 2 1]
#[2 2 3 1 2 1]
x = np.array([1, 2, 3]).reshape(1, 3)
y = np.array([7, 8, 9]).reshape(1, 3)
z = np.concatenate([x, y])
print(z)
# [[ 1 2 3]
# [ 7 8 9]]
z = np.concatenate([x, y], axis=0)
print(z)
# [[ 1 2 3]
# [ 7 8 9]]
z = np.concatenate([x, y], axis=1)
print(z)
#[[1 2 3 7 8 9]]
#在原来的维度上拼接
x = np.array([[2, 2, 3], [4, 5, 6]])
y = np.array([[4, 8, 3], [1, 2, 2]])
z = np.concatenate([x, y])
print(z)
z = np.concatenate([x, y], axis=0)
print(z)
z = np.concatenate([x, y], axis=1)
print(z)
#[[2 2 3]
#[4 5 6]
#[4 8 3]
#[1 2 2]]

#[[2 2 3]
#[4 5 6]
#[4 8 3]
#[1 2 2]]

#[[2 2 3 4 8 3]
#[4 5 6 1 2 2]]

2.numpy.stack(arrays, axis=0, out=None)
沿着新的轴加入一系列数组(stack为增加维度的拼接)。

import numpy as np
x = np.array([1, 2])
y = np.array([3, 4])
z = np.stack([x, y])
print(z.shape) 
print(z)
z = np.stack([x, y], axis=1)
print(z.shape) 
print(z)
#(2, 2)

#[[1 2]
#[3 4]]

#(2, 2)

#[[1 3]
#[2 4]]

二维数组参照1的原理。
hstack(),vstack()分别表示水平和竖直的拼接方式。在数据维度等于1时,比较特殊。而当维度大于或等于2时,它们的作用相当concatenate,用于在已有轴上进行操作。

import numpy as np 
a = np.hstack([np.array([1, 2, 3, 4]), 5])
print(a)

a = np.concatenate([np.array([1, 2, 3, 4]), 5])
print(a)
#[1 2 3 4 5]
#无法输出

所有输入数组必须具有相同的维数,但索引0处的数组具有1维,索引1处的数组具有0维。

数组的拆分

  1. numpy.split(ary, indices or sections, axis=0)将一个数组分割成多个子数组,从左到右进行拆分,如果是整数,就按照他的均数进行切分,如果是一个数组,就按他的轴进行切分。0为横向切分,1为纵向切分,一般按照横向进行切分。垂直和水平拆分可以借助函数vsplit()和hsplit()这里可以省略axis=0\1。
import numpy as np
x = np.array([[11, 12, 13, 14],
[16, 17, 18, 19],
[21, 22, 23, 24]])
y = np.split(x,[1,3],axis=0)#这里的axis=0(默认值)
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
#[21, 22, 23, 24]]), array([], shape=(0, 4), dtype=int32)]
y = np.split(x, [1, 3], axis=1)
print(y)
# [array([[11],
#[16],
#[21]]), array([[12, 13],
#[17, 18],
#[22, 23]]), array([[14],
#[19],
#[24]])]
y = np.split(x,3,axis=0)
print(y)
#[array([[11, 12, 13, 14]]), array([[16, 17, 18, 19]]), array([[21, 22, 23, 24]])]
y = np.split(x,[1],axis=0)
print(y)
#[array([[11, 12, 13, 14],
#       [16, 17, 18, 19]]), array([[21, 22, 23, 24]])]

整数和[整数]的区别在于,[x]表示的是从第几行开始拆分,而整数x是平均拆分为几行。

数组平铺

  • numpy.tile(A, reps)通过重复代表给出的次数来构造数组。A指待输入数组,reps则决定A重复的次数。
    可以对比一下下面这篇文章
    reps在不同维度下的情况
import numpy as np
x=np.array([[1,2],[2,3]])
y=np.tile(x,(1,3))
print(y)
#[[1 2 1 2 1 2]
#[2 3 2 3 2 3]]
y=np.tile(x,(3,1))
print(y)
#[[1 2]
#[2 3]
#[1 2]
#[2 3]
#[1 2]
#[2 3]]
  • numpy.repeat(a, repeats, axis=None)重复数组的元素。
    a.axis=0 ,沿着y轴复制,实际上增加了行数。
    b.axis=1 ,沿着x轴复制,实际上增加了列数。
    c.repeats ,可以为一个数,也可以为一个矩阵。
    d.axis=None 时就会flatten当前矩阵,实际上就是变成了一个行向量。
import numpy as np
x = np.repeat(3, 4)
print(x)
#[3 3 3 3]
x = np.array([[1,2],[3,4]])
y = np.repeat(x,2)
print(y)
#[1 1 2 2 3 3 4 4]
y = np.repeat(x, 2, axis=0)
print(y)
#[[1 2]
#[1 2]
#[3 4]
#[3 4]]
y = np.repeat(x, 2, axis=1)
print(y)
#[[1 1 2 2]
#[3 3 4 4]]
y = np.repeat(x, [2, 3], axis=0)
print(y)
#[[1 2]
#[1 2]
#[3 4]
#[3 4]
#[3 4]]
y = np.repeat(x, [2, 3], axis=1)
print(y)
#[[1 1 2 2 2]
#[3 3 4 4 4]]

添加和删除元素

  • numpy.unique(ar, return_index=False, return_inverse=False,return_counts=False, axis=None)找到数组中的特殊元素
    a. return_index:给出唯一值的输入数组的索引。
    b.return_inverse:重建输入数组的唯一数组的索引。
    c.return_counts:输出数组中每个唯一值出现的次数。
    numpy.unique()函数详解
  • numpy.insert(arr,obj,value,axis=None)
  • numpy.delete(arr,obj,value,axis=None)
    arr:目标向量
    obj:目标位置
    value:想要插入的数值
    axis:插入的维度
import numpy as np
a=np.array([1,1,2,3,3,4,4])
b=np.unique(a,return_counts=True)
print(b[0][list(b[1]).index(1)])
#2
#对a中,0维度,目标位1处,插入:[1,1,1,1]
x=np.array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
y=np.insert(x,1,[2,2,1,5],0)
print(y)
#[[ 0  1  2  3]
#[ 2  2  1  5]
#[ 4  5  6  7]
#[ 8  9 10 11]]
y=np.delete(x,1,0)
print(y)
#[[ 0  1  2  3]
#[ 8  9 10 11]]

若有不足之处还请大家指正,笔者定会悉心请教。

功不在戾,但求有恒。加油,奥利给!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值