Python中NumPy数组的维度变换解析

NumPy 数组的维度变换

在这里插入图片描述

reshape

numpy.reshape 函数可以在不改变数据的条件下修改形状,格式如下: numpy.reshape(arr, newshape, order=‘C’) arr:要修改形状的数组 newshape:整数或者整数数组,新的形状应当兼容原有形状 order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘k’ – 元素在内存中的出现顺序。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import numpy as np

a = np.arange(8)

print ('原始数组:')

print (a)

print ('\n')

b = a.reshape(4,2)

print ('修改后的数组:')

print (b)

原始数组:

[0 1 2 3 4 5 6 7]

修改后的数组:

[[0 1]

 [2 3]

 [4 5]

 [6 7]]

flatten

numpy.ndarray.flatten 返回一份数组拷贝,对拷贝所做的修改不会影响原始数组,格式如下:

ndarray.flatten(order=‘C’) order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘K’ – 元素在内存中的出现顺序。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import numpy as np

a = np.arange(8).reshape(2,4)

print ('原数组:')

print (a)

print ('\n')

# 默认按行

print ('展开的数组:')

print (a.flatten())

print ('\n')

print ('以 F 风格顺序展开的数组:')

print (a.flatten(order = 'F'))

原数组:

[[0 1 2 3]

 [4 5 6 7]]

展开的数组:

[0 1 2 3 4 5 6 7]

以 F 风格顺序展开的数组:

[0 4 1 5 2 6 3 7]

swapaxes

numpy.swapaxes 函数用于交换数组的两个轴,格式如下:

numpy.swapaxes(arr, axis1, axis2) arr:输入的数组 axis1:对应第一个轴的整数 axis2:对应第二个轴的整数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import numpy as np

# 创建了三维的 ndarray

a = np.arange(8).reshape(2,2,2)

print ('原数组:')

print (a)

print ('\n')

# 现在交换轴 0(深度方向)到轴 2(宽度方向)

print ('调用 swapaxes 函数后的数组:')

print (np.swapaxes(a, 2, 0))

原数组:

[[[0 1]

  [2 3]]

 [[4 5]

  [6 7]]]

调用 swapaxes 函数后的数组:

[[[0 4]

  [2 6]]

 [[1 5]

  [3 7]]]

resize

numpy.resize 函数返回指定大小的新数组。

如果新数组大小大于原始大小,则包含原始数组中的元素的副本。

numpy.resize(arr, shape) arr:要修改大小的数组 shape:返回数组的新形状

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print ('第一个数组:')

print (a)

print ('\n')

print ('第一个数组的形状:')

print (a.shape)

print ('\n')

b = np.resize(a, (3,2))

print ('第二个数组:')

print (b)

print ('\n')

print ('第二个数组的形状:')

print (b.shape)

print ('\n')

# 要注意 a 的第一行在 b 中重复出现,因为尺寸变大了

print ('修改第二个数组的大小:')

b = np.resize(a,(3,3))

print (b)

第一个数组:

[[1 2 3]

 [4 5 6]]

第一个数组的形状:

(2, 3)

第二个数组:

[[1 2]

 [3 4]

 [5 6]]

第二个数组的形状:

(3, 2)

修改第二个数组的大小:

[[1 2 3]

 [4 5 6]

 [1 2 3]]

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值