ndarray数组变换
Posted doitjust
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ndarray数组变换相关的知识,希望对你有一定的参考价值。
1 import numpy as np
维度变换
1 a = np.arange(24) 2 a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])
reshape(),视图,不修改原数组
1 a.reshape(4,6)
array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]])
1 a.reshape(2,3,4)
array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]])
1 a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])
resize() 修改原数组
1 a.resize(2,3,4)
1 a
array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]])
对数组降维,返回折叠后的一维数组,修改视图
1 a.flatten()
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])
类型变换
1 b = np.array([True,20,177.7]) 2 b,b.dtype
(array([ 1. , 20. , 177.7]), dtype(‘float64‘))
1 # 定义数组时修改类型 2 np.array([True,20,177.7],dtype=np.int)
array([ 1, 20, 177])
1 #调用数组时修改类型 #并不改变原数组 2 b 3 b.astype(np.int) #改变视图
array([ 1, 20, 177])
1 b.astype(np.unicode_)
array([‘1.0‘, ‘20.0‘, ‘177.7‘], dtype=‘<U32‘)
1 b
array([ 1. , 20. , 177.7])
以上是关于ndarray数组变换的主要内容,如果未能解决你的问题,请参考以下文章