NumPy array attributes

Let’s create a NumPy array and exemplify its attributes through examples. The list below lists NumPy array’s attributes:

  • shape
  • dtype
  • ndim
  • size
  • itemsize
  • nbytes
  • T
  • real
  • imag
  • flat

The shape property

a.shape

#out
(2, 12)

The d.type property

a.dtype

#out
dtype(‘int64’)

The ndim property

The ndim property gives the number of dimensions.

a.ndim

#out
2

The size property

The size property gives the count of elements.

a.size

#out
24

The itemsize property

The itemsize property gives the count of bytes of each element in the array.

a.itemsize

#out
8

The nbytes property

The nbytes property gives the count of bytes the whole array needs It is a.size * a.itemsize.

a.nbytes

#out
192

The T property

The T property gives the same result as transpose().

a.T

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

It transforms the array from (2, 12) into (12, 2). If the array’s rank is less than 2 then we just get a view of the array.

The real property

The real property gives the real part of an array (assuming it is an array made of complex numbers). Let’s create one.

b = np.array([1.j + 1, 2.j + 3])
b

#out
array([ 1.+1.j,  3.+2.j])
b.real

#out
array([1., 3.])

The imag property

The imag property gives the imaginary part of an array (assuming it is an array made of complex numbers).

b.imag

#out
array([1., 2.])

The flat property

The flat property gives a numpy.flatiter object. This is the only way to get a flatiter object. With the flat iterator we can loop through the array as it were a flat array.

Create a NumPy array

c = np.arange(9).reshape(3,3)
c

#out
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

Create a flatiter object

f = c.flat
f

#out
<numpy.flatiter at 0x16ab8a0>

Iterate through the new array

for item in f: print(item)

#out
0
1
2
3
4
5
6
7
8

Get an element

c.flat[6]

#out
6

Get multiple elements

c.flat[[4, 6]]

#out
array([4, 6])

Set the flat property to overwrite the entire array

c.flat = 4
c

#out
array([[4, 4, 4],
       [4, 4, 4],
       [4, 4, 4]])

We can modify certain elements in an array as shown below:

c.flat[[4, 6]] = 1
c

#out
array([[4, 4, 4],
       [4, 1, 4],
       [1, 4, 4]])

Leave a Reply