Python stores data in several different ways, but the most popular methods are list and dictionaries. The list object can store nearly ant type of Python object as an element. However, with NumPy arrays, you can only store the same type of element, e.g., all elements must be floats, integers, or strings. Comparing to list object, NumPy arrays are more efficient.
import numpy as np
# Create an array with 10^7 elements
arr = np.arange(1e7)
# Converting ndarry to list
list_arr =arr.tolist()
# List cannot be default broadcast, a function is coded to emulate
def list_times(alist, scalar):
for i, val in enumerate(alist):
alist[i] = val * scalar
return alist
# Using IPython's magic timeit command
timeit arr * 1.1
timeit list_times(larr, 1.1)
When possible, we will be working with array objects instead of lists , however, if we need linear algebra operations, we can use the matrix objects. Unlike the ndarry objects, matrix objects can only will be two dimensional.
import numpy as np
# Creating a 3D numpy array
arr = np.zeros((3, 3, 3))
# Trying to convert array to a matrix, which will not work
mat = np.matrix(arr)
# "ValueError: shape too large to be a matrix."
Array Creation and Data Typing
# Creating a list and wrap it with np.array() function
alist = [1, 2, 3]
arr = np.array(alist) # [1 2 3]
arr = np.zeros(5) # [ 0. 0. 0. 0. 0.]
# An array from 0 to 10
arr = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
# An array from 10 to 100
arr = np.arange(10, 100)
# Be careful the difference between linspace and arange
# An array from 0 to 1 with 10 steps
arr = np.linspace(0, 1 ,10)
# [ 0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556 0.66666667 0.77777778 0.88888889 1. ]
# From 1 to 100 with increment=20
arr =np.arange(1, 100, 20) # [ 1 21 41 61 81]
# Creating a 5x5 array of zero (an image)
image = np.zeros((5, 5))
# Creating a 5x5x5 array (cubic) with integer elements.
cube = np.zeros((5, 5, 5)).astype(int) + 1
# Or even simpler with 16-bit floating-point precision
cube = np.ones((5, 5, 5)).astype(np.float16)
# Array of zero integers
arr = np.zeros(2, dtype=int) # [0 0]
# Array of zero floats
arr = np.zeros(2, dtype=np.float32) # [ 0. 0.]
# Be careful of the dimension
arr = np.ones(5) # [ 1. 1. 1. 1. 1.]
print arr[0][1] # 1.0
arr = np.ones((1, 5)) # [[ 1. 1. 1. 1. 1.]]
print arr[0][1] # "invalid index to scalar variable."
Reference :
Book, Scipy and NumPy (Eli Bressert)