Python数据分析:numpy修改数组维度和连接数组

Python数据分析:numpy修改数组维度和连接数组

函数 描述
broadcast 产生模仿广播的对象
broadcast_to 将数组广播到新形状
expand_dims 扩展数组的形状
squeeze 从数组的形状中删除一维条目
numpy.broadcast 用于模仿广播的对象,返回一个对象,该对象封装了将一个数组广播到另一个数组的结果。
numpy.broadcast_to 将数组广播到新形状。它在原始数组上返回只读视图。 它通常不连续。 如果新形状不符合 NumPy 的广播规则,该函数可能会抛出ValueError。
numpy.expand_dims 通过在指定位置插入新的轴来扩展数组形状
numpy.expand_dims(arr, axis)
  • arr:输入数组
  • axis:新轴插入的位置
import numpy as np
 
x = np.array(([1,2],[3,4]))
 
print ('数组 x:')
print (x)
print ('--------------------')
y = np.expand_dims(x, axis = 0)
 
print ('数组 y:')
print (y)
print ('--------------------')
 
print ('数组 x 和 y 的形状:')
print (x.shape, y.shape)
print ('--------------------')
# 在位置 1 插入轴
y = np.expand_dims(x, axis = 1)
 
print ('在位置 1 插入轴之后的数组 y:')
print (y)
print ('--------------------')
 
print ('x.ndim 和 y.ndim:')
print (x.ndim,y.ndim)
print ('--------------------')
 
print ('x.shape 和 y.shape:')
print (x.shape, y.shape)

运行结果:
在这里插入图片描述

numpy.squeeze 从给定数组的形状中删除一维的条目
numpy.squeeze(arr, axis)
  • arr:输入数组

  • axis:整数或整数元组,用于选择形状中一维条目的子集

import numpy as np

x = np.arange(9).reshape(1,3,3)

print ('数组 x:')
print (x)
print ('--------------------')
y = np.squeeze(x)

print ('数组 y:')
print (y)
print ('--------------------')

print ('数组 x 和 y 的形状:')
print (x.shape, y.shape)

运行结果:
在这里插入图片描述

连接数组

函数 描述
concatenate 连接沿现有轴的数组序列
stack 沿着新的轴加入一系列数组。
hstack 水平堆叠序列中的数组(列方向)
vstack 竖直堆叠序列中的数组(行方向)
numpy.concatenate 沿指定轴连接相同形状的两个或多个数组
numpy.concatenate((a1, a2, ...), axis)
  • a1, a2, ...:相同类型的数组
  • axis:沿着它连接数组的轴,默认为 0
import numpy as np
 
a = np.array([[1,2],[3,4]])
 
print ('第一个数组:')
print (a)
print ('--------------------')
b = np.array([[5,6],[7,8]])
 
print ('第二个数组:')
print (b)
print ('--------------------')
# 两个数组的维度相同
 
print ('沿轴 0 连接两个数组:')
print (np.concatenate((a,b)))
print ('--------------------')
 
print ('沿轴 1 连接两个数组:')
print (np.concatenate((a,b),axis = 1))

运行结果:
在这里插入图片描述

numpy.stack 沿新轴连接数组序列
numpy.stack(arrays, axis)
  • arrays:相同形状的数组序列
  • axis:返回数组中的轴,输入数组沿着它来堆叠
numpy.hstack 通过水平堆叠来生成数组
numpy.vstack 通过垂直堆叠来生成数组
import numpy as np
 
a = np.array([[1,2],[3,4]])
 
print ('第一个数组:')
print (a)
print ('--------------------')
b = np.array([[5,6],[7,8]])
 
print ('第二个数组:')
print (b)
print ('--------------------')
 
print ('沿轴 0 堆叠两个数组:')
print (np.stack((a,b),0))
print ('--------------------')

print ('沿轴 1 堆叠两个数组:')
print (np.stack((a,b),1))
print ('--------------------')

print ('水平堆叠:')
c = np.hstack((a,b))
print (c)
print ('--------------------')

print ('竖直堆叠:')
d = np.vstack((a,b))
print (d)

运行结果:
在这里插入图片描述
参考:http://www.runoob.com/numpy

猜你喜欢

转载自blog.csdn.net/weixin_41792682/article/details/89470143