DW_numpy-数组操作

更改形状

  • numpy.ndarray.shape表示数组的维度形状,返回一个元组.通过对其赋值更改形状x.shape = (2, 4)或者[2,4]。

  • numpy.ndarray.flat 视图。 将数组转换为一维的迭代器,可以用for访问数组每一个元素。

x = np.reshape(np.arange(12),[3,4])
y = x.flat   #y是一个迭代器
print(y)
# <numpy.flatiter object at 0x0000020F9BA10C60>
for i in y:
    print(i, end=' ')
# 0 1 2 3 4 5 6 7 8 9 10 11 

y[3] = 0
print(end='\n')
print(x)        #迭代器y的改变会影响x的值(共用一个存储空间)
# [[ 0  1  2  0]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
  • numpy.ndarray.flatten([order='C'])拷贝。 将数组的副本(不同的存储空间)转换为一维数组,并返回。

    • order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘k’ – 元素在内存中的出现顺序。(简记)
  • numpy.ravel(a, order='C')返回的是视图,一个连续的扁平数组。但order=F 时是拷贝

x = np.reshape(np.arange(12),[3,4])
y = np.ravel(x) 
print(y)
# [ 0  1  2  3  4  5  6  7  8  9 10 11]
y[3] = 0   
print(x)  #同时变


#order=F 就是拷贝
y = np.ravel(x, order='F')   #等价于y = x.flatten()
print(y)
# [ 0  4  8  1  5  9  2  6 10  0  7 11]

y[3] = 0
print(x) #不变,F时是拷贝 副本
  • numpy.reshape(a, newshape[, order='C'])视图。在不更改数据的情况下为数组赋予新的形状。

    reshape()函数当参数newshape = [rows,-1]时,将根据行数自动确定列数

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

x = np.arange(12)
y = np.reshape(x,[-1,3])
print(y)
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]

z = np.reshape(y, -1)
print(z)
# [ 0 10  2  3  4  5  6  7  8  9 10 11]

数组转置

  • numpy.transpose(a, axes=None) = numpy.ndarray.T except that self is returned if self.ndim < 2.

更改维度

增加一个维度

  • numpy.newaxis = None None的别名,对索引数组很有用。 x[:, np.newaxis]
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]]

删除维度:把shape中为1的维度去掉

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

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

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,)
 
x = np.array([[[0], [1], [2]]])
print(x.shape)  # (1, 3, 1)
y = np.squeeze(x)
print(y.shape)  # (3,)
print(y)  # [0 1 2]

y = np.squeeze(x, axis=0)  #删除axis=0的维,即喊出第一维,行
print(y.shape)  # (3, 1)
y = np.squeeze(x, axis=2)
print(y.shape)  # (1, 3)
print(y)  # [[0 1 2]]

y = np.squeeze(x, axis=1)
# ValueError: cannot select an axis to squeeze out which has size not equal to one
import numpy as np
import matplotlib.pyplot as plt

x = np.array([[1, 4, 9, 16, 25]])
print(x.shape)  # (1, 5)
# plt.plot(x) 画不出来 一个空图

#转换
x = np.squeeze(x)
print(x.shape)  # (5, )
plt.plot(x)
plt.show()

数组组合

如果要将两份数据组合到一起,就需要拼接操作。

  • numpy.concatenate((a1, a2, ...), axis=0, out=None) 沿着某个轴axis拼接数组.拼接得到的数组的维度与原数组一样
x = np.array([1, 2, 3])
y = np.array([7, 8, 9])
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]
  • numpy.stack(arrays, axis = 0, out = None) 沿着新的轴加入数组,会增加数组的维度
x = np.array([1, 2, 3])
y = np.array([7, 8, 9])
z = np.stack([x, y])
print(z.shape)  # (2, 3)
print(z)
#[[1 2 3]
#[7 8 9]]
z = np.stack([x, y], axis=1)
print(z.shape)  # (3, 2)
print(z)
# [[1 7]
#  [2 8]
#  [3 9]]
x = np.array([1, 2, 3]).reshape(1, 3)
y = np.array([7, 8, 9]).reshape(1, 3)
z = np.stack([x, y])
print(z.shape)  # (2, 1, 3)
print(z)
  • 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,用于在已有轴上进行操作。

数组拆分

  • numpy.split(ary, indices_or_sections, axis=0) Split an array into multiple sub-arrays as views into ary.
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)]

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]])]

  • numpy.vsplit(ary, indices_or_sections) Split an array into multiple sub-arrays vertically (row-wise).

【例】垂直切分是把数组按照高度切分

import numpy as np

x = np.array([[11, 12, 13, 14],
              [16, 17, 18, 19],
              [21, 22, 23, 24]])
y = np.vsplit(x, 3)
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19]]), array([[21, 22, 23, 24]])]

y = np.split(x, 3)
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19]]), array([[21, 22, 23, 24]])]


y = np.vsplit(x, [1])
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
#        [21, 22, 23, 24]])]

y = np.split(x, [1])
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
#        [21, 22, 23, 24]])]


y = np.vsplit(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)]
y = np.split(x, [1, 3], axis=0)
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
#        [21, 22, 23, 24]]), array([], shape=(0, 4), dtype=int32)]
  • numpy.hsplit(ary, indices_or_sections) Split an array into multiple sub-arrays horizontally (column-wise).

【例】水平切分是把数组按照宽度切分。

import numpy as np

x = np.array([[11, 12, 13, 14],
              [16, 17, 18, 19],
              [21, 22, 23, 24]])
y = np.hsplit(x, 2)
print(y)
# [array([[11, 12],
#        [16, 17],
#        [21, 22]]), array([[13, 14],
#        [18, 19],
#        [23, 24]])]

y = np.split(x, 2, axis=1)
print(y)
# [array([[11, 12],
#        [16, 17],
#        [21, 22]]), array([[13, 14],
#        [18, 19],
#        [23, 24]])]

y = np.hsplit(x, [3])
print(y)
# [array([[11, 12, 13],
#        [16, 17, 18],
#        [21, 22, 23]]), array([[14],
#        [19],
#        [24]])]

y = np.split(x, [3], axis=1)
print(y)
# [array([[11, 12, 13],
#        [16, 17, 18],
#        [21, 22, 23]]), array([[14],
#        [19],
#        [24]])]

y = np.hsplit(x, [1, 3])
print(y)
# [array([[11],
#        [16],
#        [21]]), array([[12, 13],
#        [17, 18],
#        [22, 23]]), array([[14],
#        [19],
#        [24]])]

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]])]

数组平铺

  • 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]]

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

y = np.tile(x, (3, 3))
print(y)
# [[1 2 1 2 1 2]
#  [3 4 3 4 3 4]
#  [1 2 1 2 1 2]
#  [3 4 3 4 3 4]
#  [1 2 1 2 1 2]
#  [3 4 3 4 3 4]]
  • 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]]

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) 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

【例】查找数组的唯一元素。

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

参考文献

  • https://blog.csdn.net/csdn15698845876/article/details/73380803
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)])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值