An array object provides attributes that enable you to discover information about its structure and contents. In this section we’ll use the following arrays:
In [1]: import numpy as np
In [2]: integers = np.array([[1, 2, 3], [4, 5,6]])
In [3]: integers
Out[3]:
array([[1, 2, 3],
[4, 5, 6]])
In [4]: floats = np.array([0.0, 0.1, 0.2, 0.3,0.4])
In [5]: floats
Out[5]: array([ 0. , 0.1, 0.2, 0.3, 0.4])
NumPy does not display trailing 0s to the right of the decimal point in floating-point values.
Determining an array’s Element Type
The array function determines an array’s element type from its argument’s elements. You can check the element type with an array’s dtype attribute:
In [6]: integers.dtype
Out[6]: dtype('int64') # int32 on some platforms
In [7]: floats.dtype
Out[7]: dtype('float64')
For performance reasons, NumPy is written in the C programming language and uses C’s data types. By default, NumPy stores integers as the NumPy type int64 values which correspond to 64-bit (8-byte) integers in C—and stores floating-point numbers as the NumPy type float64 values which correspond to 64-bit (8-byte) floating-point values in C.
Determining an array’s Dimensions
The attribute ndim contains an array’s number of dimensions and the attribute shape contains a tuple
specifying an array’s dimensions:
In [8]: integers.ndim
Out[8]: 2
In [9]: floats.ndim
Out[9]: 1
In [10]: integers.shape
Out[10]: (2, 3)
In [11]: floats.shape
Out[11]: (5,)
Here, integers has 2 rows and 3 columns (6 elements) and floats is one-dimensional, so snippet [11] shows a one element tuple (indicated by the comma) containing floats’ number of elements (5).
Determining an array’s Number of Elements and Element Size
You can view an array’s total number of elements with the attribute size and the number of bytes required to store each element with itemsize:
In [12]: integers.size
Out[12]: 6
In [13]: integers.itemsize # 4 if C compiler uses
32-bit ints
Out[13]: 8
In [14]: floats.size
Out[14]: 5
In [15]: floats.itemsize
Out[15]: 8
Note that integers’ size is the product of the shape tuple’s values—two rows of three elements each for a total of six elements. In each case, itemsize is 8 because integers contains int64 values and floats contains float64 values, which each occupy 8 bytes.
Iterating Through a Multidimensional array’s Elements
You’ll generally manipulate arrays using concise functional style programming techniques. However, because arrays are iterable, you can use external iteration if you’d like:
In [16]: for row in integers:
...: for column in row:
...: print(column, end=' ')
...: print()
...:
1 2 3
4 5 6
You can iterate through a multidimensional array as if it were one-dimensional by using its flat attribute:
In [17]: for i in integers.flat:
...: print(i, end=' ')
...:
1 2 3 4 5 6
0 comments:
Post a Comment