【numpy】数组增加一维(升维)小结

every blog every motto: You can do more than you think.

0. 前言

废话: 慌也没用,能做的就是按部就班。
本文主要对python中数组增加维度进行简单小结

说明: 具体维度位置,可以自己进行调整

1. 正文

原始数据:

import numpy as np

arr = np.arange(6).reshape((2,3))
print(arr)
print('原始的shape: ',arr.shape)
print('-'*100)

在这里插入图片描述

1.1 法一

arr1 = arr[:, :, np.newaxis]
print(arr1)
print('修改后的为arr1:', arr1.shape)
print('-'*100)

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

1.2 法二

arr2 = arr.reshape(2, 3, 1)
print(arr2)
print('修改后的为arr2: ', arr2.shape)
print('-'*100)

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

1.3 法三

arr3 = np.array([arr])
print(arr3)
print('修改后的为arr3: ', arr3.shape)
print('-'*100)

在这里插入图片描述

1.4 法四

arr4 = arr[:, :, None]
print(arr4)
print('修改后的arr4:', arr4.shape)
print('-'*100)

在这里插入图片描述

1.5 法五

axis=2

arr5 = np.expand_dims(arr,axis=2)
print(arr5)
print('修改后的arr5: ',arr5.shape)
print('-'*100)

在这里插入图片描述
axis=-1,关于axis参数辨析,可参考axis小结

arr5_1 = np.expand_dims(arr, axis=-1)
print(arr5_1)
print('修改后的arr5_1:', arr5_1.shape)
print('-'*100)

在这里插入图片描述

参考文献

[1] https://www.cnblogs.com/czz0508/p/10833539.html
[2] https://blog.csdn.net/yeziand01/article/details/81458671
[3] https://www.cnblogs.com/future-dream/p/10890641.html
[4] https://blog.csdn.net/u012759006/article/details/86156259
[5] https://www.cnblogs.com/caiyishuai/p/10275809.html
[6] https://blog.csdn.net/a362682954/article/details/81220035

猜你喜欢

转载自blog.csdn.net/weixin_39190382/article/details/108799798