Numpy 简明教程

NumPy - Array Attributes

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

In this chapter, we will discuss the various array attributes of NumPy.

ndarray.shape

此数组属性返回一个包含数组维度的元组。它还可用于调整数组大小。

This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array.

Example 1

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

输出如下 −

The output is as follows −

(2, 3)

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

输出如下 −

The output is as follows −

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

Example 3

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

NumPy also provides a reshape function to resize an array.

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

输出如下 −

The output is as follows −

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

ndarray.ndim

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

This array attribute returns the number of array dimensions.

Example 1

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

输出如下 −

The output is as follows −

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

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

输出如下 −

The output is as follows −

[[[ 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

此 array 属性以字节返回数组中每个元素的长度。

This array attribute returns the length of each element of array in bytes.

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

输出如下 −

The output is as follows −

1

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

输出如下 −

The output is as follows −

4

numpy.flags

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

The ndarray object has the following attributes. Its current values are returned by this function.

Sr.No.

Attribute & Description

1

C_CONTIGUOUS © The data is in a single, C-style contiguous segment

2

F_CONTIGUOUS (F) The data is in a single, Fortran-style contiguous segment

3

OWNDATA (O) The array owns the memory it uses or borrows it from another object

4

WRITEABLE (W) The data area can be written to. Setting this to False locks the data, making it read-only

5

ALIGNED (A) The data and all elements are aligned appropriately for the hardware

6

UPDATEIFCOPY (U) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array

Example

以下示例展示标记的当前值。

The following example shows the current values of flags.

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

输出如下 −

The output is as follows −

C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False