7.3 array Attributes

  • attributes enable you to discover information about its structure and contents
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

Determining an array’s Element Type

In [6]:
integers.dtype
Out[6]:
dtype('int64')
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
  • Other NumPy types

Determining an array’s Dimensions

  • ndim contains an array’s number of dimensions
  • 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,)

Determining an array’s Number of Elements and Element Size

  • view an array’s total number of elements with size
  • view number of bytes required to store each element with itemsize
In [12]:
integers.size
Out[12]:
6
In [13]:
integers.itemsize
Out[13]:
8
In [14]:
floats.size
Out[14]:
5
In [15]:
floats.itemsize
Out[15]:
8

Iterating through a Multidimensional array’s Elements

In [16]:
for row in integers:
    for column in row:
        print(column, end='  ')
    print() 
1  2  3  
4  5  6  
  • Iterate through a multidimensional array as if it were one-dimensional by using flat
In [17]:
for i in integers.flat:
    print(i, end='  ')
1  2  3  4  5  6  

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.