7.2 Creating arrays from Existing Data

The NumPy documentation recommends importing the numpy module as np so that you can access its members with "np.":

In [1]: import numpy as np

The numpy module provides various functions for creating arrays. Here we use the array function, which receives as an argument an array or other collection of elements and returns a new array containing the argument’s elements. Let’s pass a list:

In [2]: numbers = np.array([2, 3, 5, 7, 11])

The array function copies its argument’s contents into the array. Let’s look at the type of object that function array returns and display its contents:

In [3]: type(numbers)
Out[3]: numpy.ndarray

In [4]: numbers
Out[4]: array([ 2, 3, 5, 7, 11])

Note that the type is numpy.ndarray, but all arrays are output as “array.” When outputting an array, NumPy separates each value from the next with a comma and a space and right-aligns all the values using the same field width. It determines the field width based on the value that occupies the largest number of character positions. In this case, the value 11 occupies the two character positions, so all the values are formatted in two-character fields. That’s why there’s a leading space between the [ and 2.

Multidimensional Arguments

The array function copies its argument’s dimensions. Let’s create an array from a two-row-by-three-column list:

In [5]: np.array([[1, 2, 3], [4, 5, 6]])
Out[5]:
array([[1, 2, 3],
       [4, 5, 6]])

NumPy auto-formats arrays, based on their number of dimensions, aligning the columns within each row.

tick mark Self Check

  1. (Fill-In) Function array creates an array from             .
    Answer: an array or other collection of elements.

  2. (IPython Session) Create a one-dimensional array from a list comprehension that produces the even integers from 2 through 20.
    Answer:

    In [1]: import numpy as np
    
    In [2]: np.array([x for x in range(2, 21, 2)])
    Out[2]: array([ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
    
  3. (IPython Session) Create a 2-by-5 array containing the even integers from 2 through 10 in the first row and the odd integers from 1 through 9 in the second row.
    Answer:

    In [3]: np.array([[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]])
    Out[3]:
    array([[ 2, 4, 6, 8, 10],
           [ 1, 3, 5, 7, 9]])
    
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.239.46