7.5 Creating arrays from Ranges

  • NumPy provides optimized functions for creating arrays from ranges

Creating Integer Ranges with arange

In [1]:
import numpy as np
In [2]:
np.arange(5)
Out[2]:
array([0, 1, 2, 3, 4])
In [3]:
np.arange(5, 10)
Out[3]:
array([5, 6, 7, 8, 9])
In [4]:
np.arange(10, 1, -2)
Out[4]:
array([10,  8,  6,  4,  2])

Creating Floating-Point Ranges with linspace

  • Produce evenly spaced floating-point ranges with NumPy’s linspace function
  • Ending value is included in the array
In [5]:
np.linspace(0.0, 1.0, num=5)
Out[5]:
array([0.  , 0.25, 0.5 , 0.75, 1.  ])

Reshaping an array

  • array method reshape transforms an array into different number of dimensions
  • New shape must have the same number of elements as the original
In [6]:
np.arange(1, 21).reshape(4, 5)
Out[6]:
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20]])

Displaying Large arrays

  • When displaying an array, if there are 1000 items or more, NumPy drops the middle rows, columns or both from the output
In [7]:
np.arange(1, 100001).reshape(4, 25000)
Out[7]:
array([[     1,      2,      3, ...,  24998,  24999,  25000],
       [ 25001,  25002,  25003, ...,  49998,  49999,  50000],
       [ 50001,  50002,  50003, ...,  74998,  74999,  75000],
       [ 75001,  75002,  75003, ...,  99998,  99999, 100000]])
In [8]:
np.arange(1, 100001).reshape(100, 1000)
Out[8]:
array([[     1,      2,      3, ...,    998,    999,   1000],
       [  1001,   1002,   1003, ...,   1998,   1999,   2000],
       [  2001,   2002,   2003, ...,   2998,   2999,   3000],
       ...,
       [ 97001,  97002,  97003, ...,  97998,  97999,  98000],
       [ 98001,  98002,  98003, ...,  98998,  98999,  99000],
       [ 99001,  99002,  99003, ...,  99998,  99999, 100000]])

©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.