Adding Data to Arrays

NumPy provides methods zeros, ones and full for creating arrays containing 0s, 1s or a specified value, respectively. By default, zeros and ones create arrays containing float64 values. We’ll show how to customize the element type momentarily. The first argument to these functions must be an integer. For an integer, each function returns a one-dimensional array with the specified number of elements:

import numpy as np

x = np.zeros(5) # x will store: [0.0, 0.0, 0.0, 0.0, 0.0]

Arrays from Integer Ranges:

NumPy provides optimized functions for creating arrays from ranges. We focus on simple evenly spaced integer and floating-point ranges, but NumPy also supports nonlinear ranges. Let’s use NumPy’s `arange` method to create integer ranges—similar to using built-in function range. In each case, `arange` first determines the resulting array’s number of elements, allocates the memory, then stores the specified range of values in the array:
import numpy as np
y = np.arange(5) # [0, 1, 2, 3, 4, 5]
z = np.arange(5, 10) # [5, 6, 7, 8, 9]
a = np.arange(10, 1, -2) # [10, 8, 6, 4, 2]

Arrays from Float Ranges:

You can produce evenly spaced floating-point ranges with NumPy’s `linspace` method. The method’s first two arguments specify the starting and ending values in the range, and the ending value is included in the array. The optional keyword argument `num` specifies the number of evenly spaced values to produce (this argument’s default value is 50):
import numpy as np
arr = np.linspace(0.0, 1.0, num = 5) # [0.0  ,  0.25,  0.5 ,  0.75,  1.0]

Reshaping Arrays:

You also can create an array from a range of elements, then use array method `reshape` to transform the one-dimensional array into a multidimensional array. Let’s create an array containing the values from 1 through 20, then reshape it into four rows by five columns:
import numpy as np
arr1 = np.arange(1, 20)
arr1.reshape(4, 5)

"""
The array looks like this now:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
"""

# You can also chain method calls to accomplish the same thing:
arr2 = np.arange(1, 20).reshape(4, 5)

Note the chained method calls in the second part of the example above. First, arange produces an array containing the values 1–20. Then we call reshape on that array to get the 4-by-5 array that was displayed.

You can reshape any array, provided that the new shape has the same number of elements as the original. So a six-element one-dimensional array can become a 3-by-2 or 2- by-3 array, and vice versa, but attempting to reshape a 15-element array into a 4-by-4 array (16 elements) causes a ValueError.