Creating NumPy arrays
There are several ways to create objects of ndarray
type. The recipes in this chapter provide a comprehensive list of the possibilities.
How to do it…
Let's move on to learn how an array can be created from a list.
Creating an array from a list
To create an array from an explicit list, use the following code:
x = np.array([2, 3.5, 5.2, 7.3])
This will assign to x
the following array object:
array([ 2. , 3.5, -1. , 7.3, 0. ])
Notice that integer array entries are converted to floating point values. NumPy arrays are homogeneous, that is, all elements of an array must have the same type. Upon creation, elements in the input list are converted to a common type by a process known as casting. In the preceding example, all elements are cast to floats.
To create a multidimensional array, use a list of lists:
A = np.array([[1, -3, 2],[2, 0, 1]])
This creates the array:
array([[ 1, -3, 2], [ 2, 0, 1]])
The array elements in this example are integers. Creating arrays with more than...