array
s from Existing DataThe 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 array
s. 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 array
s 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
.
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 array
s, based on their number of dimensions, aligning the columns within each row.
(Fill-In) Function array
creates an array
from .
Answer: an array
or other collection of elements.
(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])
(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]])
18.216.239.46