numpy
numpy
1
Numpy
• Numerical Python
• Developed in 2005 by Travis Oliphant
• Lingua franca for data exchange
• ndarray – a n-dimensional array
• Fast operations on entire arrays
• Reading/writing array data
• Linear algebra operations Travis Oliphant
2
nd-array
• A fast, flexible container for large datasets
in Python
• Homogeneous data i.e. all of the elements
must be the same type
3
Creating ndarray
• np.array(): convert input data to an
ndarray
• np.zeros(): produces arrays of 0s
• np.ones(): produces arrays of 1s
• np.empty(): create new arrays by
allocating new memory, but do not
populate with any values
• np.arange(): like the built-in range but
returns an ndarray instead of a list
4
Examples
5
Summary of array creation
functions
6
Attributes of numpy array
• shape: a tuple indicating the size of each
dimension
• dtype: an object describing the data type
of the array
• ndim: the number of dimensions of the
array
7
shape attribute
8
Numpy data types
9
Vectorization
• Express batch operations on data without
writing any for loops
• Any arithmetic operations between equal-size
arrays applies the operation element-wise
• Arithmetic operations with scalars propagate
the scalar argument to each element in the
array
• Comparisons between arrays of the same
size yield boolean arrays
• Operations between differently sized arrays is
called broadcasting
10
Slicing
• Array slices are views on the original array
• Format
– start: end: step
11
Element-wise array functions
12
np.where()
13
Mathematical and Statistical
Methods
• mean(): returns the mean value computed
over the array
• cumsum(): returns the cumulative sum of
array elements
• cumprod(): returns the cumulative product
of array elements
Methods for boolean arrays
• sum(): counting True values in a boolean
array
• any(): tests whether one or more values in
an array is True
• all(): checks if every value is True
Unique
Linear algebra functions
Reshape
18
Converting to 1D array
• flatten()
• ravel()
19
concatenate
20
Convenience functions
• vstack: stack arrays row-wise (along axis
0)
• hstack: stack arrays column-wise (along
axis 1)
21
Splitting an array
22