Numpy3_数组的操作_Datawhale十月组队学习

Numpy学习|数组的操作


涉及更改形状、维度;数组组合、拆分、平铺;添加删除操作等

1.更改形状


(1)直接更改shape属性

import numpy as np

x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
print(x.shape)  # (8,)
x.shape = [2, 4]
print(x)
# [[1 2 9 4]
#  [5 6 7 8]]

(2)order操作
numpy.ndarray.flatten([order=‘C’]) 将数组的副本转换为一维数组,并返回。
order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘k’ – 元素在内存中的出现顺序。(简记)

numpy.ravel(a, order=‘C’)Return a contiguous flattened array.返回视图

numpy.reshape(a, newshape[, order=‘C’])在不更改数据的情况下为数组赋予新的形状。
当参数newshape = [rows,-1]时,将根据行数自动确定列数。

import numpy as np
arr =  np.array([[16, 17, 18, 19, 20],[11, 12, 13, 14, 15],[21, 22, 23, 24, 25],[31, 32, 33, 34, 35],[26, 27, 28, 29, 30]])
y = arr.flatten(order='F')
print(y)


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, [3, -1])
print(y)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

y = np.reshape(x,[-1,3])
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对应元素也改变)


2.更改维度


(1)当创建一个数组之后,还可以给它增加一个维度,这在矩阵计算中经常会用到。

numpy.newaxis = None None的别名,对索引数组很有用。

【例】很多工具包在进行计算时都会先判断输入数据的维度是否满足要求,如果输入数据达不到指定的维度时,可以使用newaxis参数来增加一个维度。

import numpy as np

x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
print(x.shape)  # (8,)
print(x)  # [1 2 9 4 5 6 7 8]

y = x[np.newaxis, :]
print(y.shape)  # (1, 8)
print(y)  # [[1 2 9 4 5 6 7 8]]

y = x[:, np.newaxis]
print(y.shape)  # (8, 1)
print(y)
# [[1]
#  [2]
#  [9]
#  [4]
#  [5]
#  [6]
#  [7]
#  [8]]

(2)从数组的形状中删除单维度条目,即把shape中为1的维度去掉。

numpy.squeeze(a, axis=None) 从数组的形状中删除单维度条目,即把shape中为1的维度去掉。
a表示输入的数组;
axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;

在机器学习和深度学习中,通常算法的结果是可以表示向量的数组(即包含两对或以上的方括号形式[[]]),如果直接利用这个数组进行画图可能显示界面为空(见后面的示例)。我们可以利用squeeze()函数将表示向量的数组转换为秩为1的数组,这样利用 matplotlib 库函数画图时,就可以正常的显示结果了。

import numpy as np

x = np.arange(10)
print(x.shape)  # (10,)
x = x[np.newaxis, :]
print(x.shape)  # (1, 10)
y = np.squeeze(x)
print(y.shape)  # (10,)


import numpy as np
import matplotlib.pyplot as plt

x = np.array([[1, 4, 9, 16, 25]])
x = np.squeeze(x)
print(x.shape)  # (5, )
plt.plot(x)
plt.show()

3.数组的拼接


(1)numpy.concatenate((a1, a2, …), axis=0, out=None) Join a sequence of arrays along an existing axis.
连接沿现有轴的数组序列(原来x,y都是一维的,拼接后的结果也是一维的)

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

(3)numpy.vstack(tup)Stack arrays in sequence vertically (row wise).
numpy.hstack(tup)Stack arrays in sequence horizontally (column wise).
hstack(),vstack()分别表示水平和竖直的拼接方式。在数据维度等于1时,比较特殊。而当维度大于或等于2时,它们的作用相当于concatenate,用于在已有轴上进行操作。

4.数组拆分


numpy.split(ary, indices_or_sections, axis=0) Split an array into multiple sub-arrays as views into ary.
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])
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
#        [21, 22, 23, 24]]), array([], shape=(0, 4), dtype=int32)]

5.数组平铺


(1)numpy.tile(A, reps) Construct an array by repeating A the number of times given by reps.
tile是瓷砖的意思,顾名思义,这个函数就是把数组像瓷砖一样铺展开来。

import numpy as np

x = np.array([[1, 2], [3, 4]])
print(x)
# [[1 2]
#  [3 4]]

y = np.tile(x, (1, 3))
print(y)
# [[1 2 1 2 1 2]
#  [3 4 3 4 3 4]

(2)重复数组的元素
• numpy.repeat(a, repeats, axis=None) Repeat elements of an array.
axis=0,沿着y轴复制,实际上增加了行数。
axis=1,沿着x轴复制,实际上增加了列数。
repeats,可以为一个数,也可以为一个矩阵。
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]]

6.唯一元素查找


• numpy.unique(ar, return_index=False, return_inverse=False,return_counts=False, axis=None) Find the unique elements of an array.

return_index:the indices of the input array that give the unique values
return_inverse:the indices of the unique array that reconstruct the input array
return_counts:the number of times each unique value comes up in the input array

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

Test


(1)给定两个随机数组A和B,验证它们是否相等。
import numpy as np
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
print(A,B)
np.equal(A,B)# 判断每个元素是否相似
np.array_equal(A,B)# 判断两个数组是否相等
np.allclose(A,B)# 方法二判断数组是否相等

(2)在给定的numpy数组中找到重复的条目(第二次出现以后),并将它们标记为True。第一次出现应为False。

import numpy as np
a = np.random.randint(0, 5, 10)
u, indices = np.unique(a, return_index=True)
print(a,u,indices)
bool_a = np.repeat(True,10)
bool_a[indices] = False
print(bool_a)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Arya's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值