目录

NumPy - 数组属性( Array Attributes)

在本章中,我们将讨论NumPy的各种数组属性。

ndarray.shape

此数组属性返回由数组维度组成的元组。 它也可以用于调整阵列的大小。

例子1 (Example 1)

import numpy as np 
a = np.array([[1,2,3],[4,5,6]]) 
print a.shape

输出如下 -

(2, 3)

例子2 (Example 2)

# this resizes the ndarray 
import numpy as np 
a = np.array([[1,2,3],[4,5,6]]) 
a.shape = (3,2) 
print a 

输出如下 -

[[1, 2] 
 [3, 4] 
 [5, 6]]

例子3 (Example 3)

NumPy还提供了重塑函数来调整数组大小。

import numpy as np 
a = np.array([[1,2,3],[4,5,6]]) 
b = a.reshape(3,2) 
print b

输出如下 -

[[1, 2] 
 [3, 4] 
 [5, 6]]

ndarray.ndim

此数组属性返回数组维数。

例子1 (Example 1)

# an array of evenly spaced numbers 
import numpy as np 
a = np.arange(24) 
print a

输出如下 -

[0 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16 17 18 19 20 21 22 23] 

例子2 (Example 2)

# this is one dimensional array 
import numpy as np 
a = np.arange(24) 
a.ndim  
# now reshape it 
b = a.reshape(2,4,3) 
print b 
# b is having three dimensions

输出如下 -

[[[ 0,  1,  2] 
  [ 3,  4,  5] 
  [ 6,  7,  8] 
  [ 9, 10, 11]]  
  [[12, 13, 14] 
   [15, 16, 17]
   [18, 19, 20] 
   [21, 22, 23]]] 

numpy.itemsize

此数组属性以字节为单位返回数组的每个元素的长度。

例子1 (Example 1)

# dtype of array is int8 (1 byte) 
import numpy as np 
x = np.array([1,2,3,4,5], dtype = np.int8) 
print x.itemsize

输出如下 -

1

例子2 (Example 2)

# dtype of array is now float32 (4 bytes) 
import numpy as np 
x = np.array([1,2,3,4,5], dtype = np.float32) 
print x.itemsize

输出如下 -

4

numpy.flags

ndarray对象具有以下属性。 其当前值由此函数返回。

Sr.No. 属性和描述
1

C_CONTIGUOUS (C)

数据位于单个C风格的连续段中

2

F_CONTIGUOUS (F)

数据位于Fortran风格的单个连续段中

3

OWNDATA (O)

该数组拥有它使用的内存或从另一个对象借用它

4

WRITEABLE (W)

可以写入数据区域。 将此设置为False将锁定数据,使其成为只读

5

ALIGNED (A)

数据和所有元素都适合硬件对齐

6

UPDATEIFCOPY (U)

此数组是其他一些数组的副本。 取消分配此数组时,将使用此数组的内容更新基本数组

例子 (Example)

以下示例显示了标志的当前值。

import numpy as np 
x = np.array([1,2,3,4,5]) 
print x.flags

输出如下 -

C_CONTIGUOUS : True 
F_CONTIGUOUS : True 
OWNDATA : True 
WRITEABLE : True 
ALIGNED : True 
UPDATEIFCOPY : False
↑回到顶部↑
WIKI教程 @2018