3.2 NumPy Arrays
3.2 NumPy Arrays
NumPy Ndarray
Ndarray is the n-dimensional array object defined in the numpy which stores the
collection of the similar type of elements. In other words, we can define a ndarray as the
collection of the data type (dtype) objects.
The ndarray object can be accessed by using the 0 based indexing. Each element of the
Array object contains the same size in the memory.
1. >>> a = numpy.array
Example
import numpy as np
print(arr)
print(type(arr))
type(): This built-in Python function tells us the type of the object passed to it. Like in above
code it shows that arr is numpy.ndarray type.
To create an ndarray, we can pass a list, tuple or any array-like object into
the array() method, and it will be converted into an ndarray:
Example
Use a tuple to create a NumPy array:
import numpy as np
print(arr)
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example
Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
import numpy as np
print(arr)
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
NumPy has a whole sub module dedicated towards matrix operations called numpy.mat
Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
print(arr)
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
Example
Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and
4,5,6:
import numpy as np
print(arr)
Example
Check how many dimensions the arrays have:
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Higher Dimensional Arrays
An array can have any number of dimensions.
When the array is created, you can define the number of dimensions by using
the ndmin argument.
Example
Create an array with 5 dimensions and verify that it has 5 dimensions:
import numpy as np
print(arr)
print('number of dimensions :', arr.ndim)
In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element
that is the vector, the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim
has 1 element that is 3D array and 1st dim has 1 element that is a 4D array.
We can also pass a collection object into the array routine to create the equivalent n-
dimensional array. The syntax is given below.
1. >>> numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
S Parameter Description
N
1 object It represents the collection object. It can be a list, tuple, dictionary, set,
etc.
2 dtype We can change the data type of the array elements by changing this
option to the specified type. The default is none.
5 subok The returned array will be base class array by default. We can change
this to make the subclasses passes through by setting this option to
true.
To change the data type of the array elements, mention the name of the data type along
with the collection.
import numpy as np
arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])
Print arr
print(arr.ndim)
Finding the size of each array element
The itemsize function is used to get the size of each array item. It returns the number of
bytes taken by each array element.
Example
1. #finding the size of each item in the array
2. import numpy as np
3. a = np.array([[1,2,3]])
4. print("Each item contains",a.itemsize,"bytes")
Output:
Example
1. #finding the data type of each array item
2. import numpy as np
3. a = np.array([[1,2,3]])
4. print("Each item is of the type",a.dtype)
Output:
------------------------------------------------------------
The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the
second has index 1 etc.
Example
Get the first element from the following array:
import numpy as np
print(arr[0])
Example
Get the second element from the following array.
import numpy as np
print(arr[1])
Example
Get third and fourth elements from the following array and add them.
import numpy as np
print(arr[2] + arr[3])
-------------------------------------------------------
Access 2-D Arrays
To access elements from 2-D arrays we can use comma separated integers representing the
dimension and the index of the element.
Think of 2-D arrays like a table with rows and columns, where the dimension represents the
row and the index represents the column.
Example
Access the element on the first row, second column:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
Example
Access the element on the 2nd row, 5th column:
import numpy as np
Example
Access the third element of the second array of the first array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr)
print(arr[0, 1, 2])
Example Explained
arr[0, 1, 2] prints the value 6.
The first number represents the first dimension, which contains two arrays:
and:
[[7, 8, 9], [10, 11, 12]]
The second number represents the second dimension, which also contains two arrays:
[1, 2, 3]
and:
[4, 5, 6]
The third number represents the third dimension, which contains three values:
4
5
6
Since we selected 2, we end up with the third value:
6
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]],[[67, 98,
79], [180, 181, 122]]])
print(arr)
print(arr[2, 1, 2])
o/p
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[ 10 11 12]]
[[ 67 98 79]
122
Example
Print the last element from the 2nd dim:
import numpy as np
Any item extracted from ndarray object (by slicing) is represented by a Python
object of one of array scalar types. The following diagram shows a relationship
between ndarray, data type object (dtype) and array scalar type −
An instance of ndarray class can be constructed by different array creation
routines.The basic ndarray is created using an array function in NumPy as
follows −
numpy.array
Sr.No
Parameter & Description
.
object
1
Any object exposing the array interface method returns an array, or any (nested)
sequence.
2 dtype
Desired data type of array, optional
3 copy
Optional. By default (true), the object is copied
4 order
C (row major) or F (column major) or A (any) (default)
subok
5
By default, returned array forced to be a base class array. If true, sub-classes
passed through
6 ndmin
Specifies minimum dimensions of resultant array
Example 1
import numpy as np
a = np.array([1,2,3])
print a
[1, 2, 3]
Example 2
# more than one dimensions
import numpy as np
a = np.array([[1, 2], [3, 4]])
print a
print(a.
[[1, 2]
[3, 4]]
Example 3
# minimum dimensions
import numpy as np
a = np.array([1, 2, 3,4,5], ndmin = 2)
print(a)
[[1, 2, 3, 4, 5]]
Example 4
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print a
Example
Print the shape of a 2-D array:
import numpy as np
print(arr.shape)
The example above returns (2, 4), which means that the array has 2 dimensions, where the
first dimension has 2 elements and the second has 4.
To get the shape and size of the array, the size and shape function associated with the
numpy array is used.
Output:
Array Size: 7
Shape: (1, 7)
Example
Create an array with 5 dimensions using ndmin using a vector with values 1,2,3,4 and verify
that last dimension has value 4:
import numpy as np
print(arr)
print('shape of array :', arr.shape)
In the example above at index-4 we have value 4, so we can say that 5th ( 4 + 1 th)
dimension has 4 elements.
Reshaping arrays
Reshaping means changing the shape of an array.
The reshape() function associated with the ndarray object is used to reshape the array. It
accepts the two parameters indicating the row and columns of the new shape of the array.
Example
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print("printing the original array..")
print(a)
print(a.shape)
a=a.reshape(2,3)
print("printing the reshaped array..")
print(a)
Output:
import numpy as np
newarr = arr.reshape(4, 3)
print(newarr)
The outermost dimension will have 2 arrays that contains 3 arrays, each with 2 elements:
import numpy as np
newarr = arr.reshape(2, 3, 2)
print(newarr)
Example
Try converting 1D array with 8 elements to a 2D array with 3 elements in each dimension
(will raise an error):
import numpy as np
newarr = arr.reshape(3, 3)
print(newarr)
import numpy as np
print(arr.reshape(2, 4).base)
------------------------------------------------------------------------------
Unknown Dimension
You are allowed to have one "unknown" dimension.
Meaning that you do not have to specify an exact number for one of the dimensions in the
reshape method.
Pass -1 as the value, and NumPy will calculate this number for you.
Example
Convert 1D array with 8 elements to 3D array with 2x2 elements:
import numpy as np
print(newarr)
-----------------------------------------------------
Example
Convert the array into a 1D array:
import numpy as np
newarr = arr.reshape(-1)
print(newarr)
Using the numpy.flatten() method.
As the name applies, the flatten() method in Numpy is used to convert an array into a 1-
dimensional array. So it basically flattens the array irrespective of its shape. Using the
flatten() method does not have a required parameter. See an example below.
import numpy as np
print(a)
print('flattening a...')
print(a.flatten())
Output:
[[1 2 3]
[4 5 6]
[7 8 9]]
flattening a...
[1 2 3 4 5 6 7 8 9]
Example
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print(a)
print(a[0,1])
print(a[2,0])
Output:
2
5
The above program prints the 2nd element from the 0th index and 0th element from the
2nd index of the array.
Linspace
The linspace() function returns the evenly spaced values over the given interval. The
following example returns the 10 evenly separated values over the given interval 5-15
Example
import numpy as np
a=np.linspace(5,15,10) #prints 10 values which are evenly spaced over the given interval 5-
15
print(a)
Output:
Example
1. import numpy as np
2. a = np.array([1,2,3,10,15,4])
3. print("The array:",a)
4. print("The maximum element:",a.max())
5. print("The minimum element:",a.min())
6. print("The sum of the elements:",a.sum())
Output:
The array: [ 1 2 3 10 15 4]
The maximum element: 15
The minimum element: 1
The sum of the elements: 35
Sr.No
Data Types & Description
.
1 bool_
Boolean (True or False) stored as a byte
2 int_
Default integer type (same as C long; normally either int64 or int32)
3 intc
Identical to C int (normally int32 or int64)
4 intp
Integer used for indexing (same as C ssize_t; normally either int32 or int64)
5 int8
Byte (-128 to 127)
6 int16
Integer (-32768 to 32767)
7 int32
Integer (-2147483648 to 2147483647)
8 int64
Integer (-9223372036854775808 to 9223372036854775807)
9 uint8
Unsigned integer (0 to 255)
10 uint16
Unsigned integer (0 to 65535)
11 uint32
Unsigned integer (0 to 4294967295)
12 uint64
Unsigned integer (0 to 18446744073709551615)
13 float_
Shorthand for float64
14 float16
Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
15 float32
Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
16 float64
Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
17 complex_
Shorthand for complex128
complex64
18
Complex number, represented by two 32-bit floats (real and imaginary
components)
complex128
19
Complex number, represented by two 64-bit floats (real and imaginary
components)
NumPy numerical types are instances of dtype (data-type) objects, each having
unique characteristics. The dtypes are available as np.bool_, np.float32, etc.
The byte order is decided by prefixing '<' or '>' to data type. '<' means that
encoding is little-endian (least significant is stored in smallest address). '>'
means that encoding is big-endian (most significant byte is stored in smallest
address).
int32
Example 2
#int8, int16, int32, int64 can be replaced by equivalent string 'i1', 'i2','i4', etc.
import numpy as np
dt = np.dtype('i4')
print dt
The output is as follows −
int32
Example 3
# using endian notation
import numpy as np
dt = np.dtype('>i4')
print dt
>i4
The following examples show the use of structured data type. Here, the field
name and the corresponding scalar data type is to be declared.
Example 4
# first create structured data type
import numpy as np
dt = np.dtype([('age',np.int8)])
print dt
[('age', 'i1')]
Example 5
# now apply it to ndarray object
import numpy as np
dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype = dt)
print a
dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype = dt)
print a['age']
[10 20 30]
Example 7
The following examples define a structured data type called student with a
string field 'name', an integer field 'age' and a float field 'marks'. This dtype is
applied to ndarray object.
import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
print student
Example 8
import numpy as np
Each built-in data type has a character code that uniquely identifies it.
'b' − boolean
'i' − (signed) integer
'u' − unsigned integer
'f' − floating-point
'c' − complex-floating point
'm' − timedelta
'M' − datetime
'O' − (Python) objects
'S', 'a' − (byte-)string
'U' − Unicode
'V' − raw data (void)
NumPy dtype
All the items of a numpy array are data type objects also known as numpy dtypes. A data
type object implements the fixed size of memory corresponding to an array.
Align: It can be set to any boolean value. If true, then it adds extra padding to make it
equivalent to a C struct.
Example 1
1. import numpy as np
2. d = np.dtype(np.int32)
3. print(d)
Output:
int32
Example 2
1. import numpy as np
2. d = np.int32(i4)
3. print(d)
Output:
int32
Example
Get the data type of an array object:
import numpy as np
print(arr.dtype)
Example
Get the data type of an array containing strings:
import numpy as np
print(arr.dtype)
Example
Create an array with data type string:
import numpy as np
print(arr)
print(arr.dtype)
Example
Create an array with data type 4 bytes integer:
import numpy as np
print(arr)
print(arr.dtype)
ValueError: In Python ValueError is raised when the type of passed argument to a function
is unexpected/incorrect.
Example
A non integer string like 'a' can not be converted to integer (will raise an error):
import numpy as np
The astype() function creates a copy of the array, and allows you to specify the data type as a
parameter.
The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or you can
use the data type directly like float for float and int for integer.
Example
Change data type from float to integer by using 'i' as parameter value:
import numpy as np
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
Example
Change data type from float to integer by using int as parameter value:
import numpy as np
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)
Example
Change data type from integer to boolean:
import numpy as np
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)
Example 1
import numpy as np
d = np.dtype([('salary',np.float)])
print(d)
Output:
Example 2
import numpy as np
d=np.dtype([('salary',np.float)])
arr = np.array([(10000.12,),(20000.50,)],dtype=d)
print(arr['salary'])
Output:
This array attribute returns a tuple consisting of array dimensions. It can also be
used to resize the array.
Example 1
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print a.shape
(2, 3)
Example 2
# this resizes the ndarray
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a.shape = (3,2)
print a
[[1, 2]
[3, 4]
[5, 6]]
-----------------------------------------------------------------------------------------------------------
Example 3
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a.ndim)
b = a.reshape(3,2)
print b
The output is as follows −
[[1, 2]
[3, 4]
[5, 6]]
ndarray.ndim
Arange
The arange([start,] stop[, step,][, dtype]) : Returns an array with evenly
spaced elements as per the interval. The interval mentioned is half-opened i.e.
[Start, Stop)
Parameters :
start : [optional] start of interval range. By default start =
0
stop : end of interval range
step : [optional] step size of interval. By default step size
= 1,
For any output out, this is the distance between two adjacent
values, out[i+1] - out[i].
dtype : type of output array
Return:
Array of evenly spaced values.
Length of array being generated = Ceil((Stop - Start) / Step)
Example:
# numpy.arange method
import numpy as np
print("A\n", np.arange(4),"\n")
print("A\n", np.arange(4).reshape(2, 2), "\n")
Output :
A[0,1,2,3]
A
[[0 1]
[2 3]]
A
[4 5 6 7 8 9]
A
[ 4 7 10 13 16 19]
.
Example:
Python3
# numpy.arange method
import numpy as np
print(np.arange(1, 2, 0.1))
Output:
[1.1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]
Example 1
# an array of evenly spaced numbers
import numpy as np
a = np.arange(24)
print a
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
Example 2
# this is one dimensional array
import numpy as np
a = np.arange(24)
print(a)
print(a.ndim )
# now reshape it
b = a.reshape(2,4,3)
print b
pr
# b is having three dimensions
[[[ 0, 1, 2]
[ 3, 4, 5]
[ 6, 7, 8]
[ 9, 10, 11]]
[[12, 13, 14]
[15, 16, 17]
[18, 19, 20]
[21, 22, 23]]]
numpy.itemsize
This array attribute returns the length of each element of array in bytes.
Example 1
# dtype of array is int8 (1 byte)
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.int8)
print x.itemsize
Example 2
# dtype of array is now float32 (4 bytes)
import numpy as np
x = np.array([1,2,3,4,5], dtype = float32)
print x.itemsize
numpy.flags
The ndarray object has the following attributes. Its current values are returned
by this function.
Sr.No
Attribute & Description
.
1 C_CONTIGUOUS (C)
The data is in a single, C-style contiguous segment
2 F_CONTIGUOUS (F)
The data is in a single, Fortran-style contiguous segment
3 OWNDATA (O)
The array owns the memory it uses or borrows it from another object
WRITEABLE (W)
4
The data area can be written to. Setting this to False locks the data, making it
read-only
5 ALIGNED (A)
The data and all elements are aligned appropriately for the hardware
UPDATEIFCOPY (U)
6
This array is a copy of some other array. When this array is deallocated, the base
array will be updated with the contents of this array
Example
import numpy as np
x = np.array([1,2,3,4,5])
print x.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
NumPy - Array Creation Routines
A new ndarray object can be constructed by any of the following array creation
routines or using a low-level ndarray constructor.
numpy.empty
1 Shape
Shape of an empty array in int or tuple of int
2 Dtype
Desired output data type. Optional
3 Order
'C' for C-style row-major array, 'F' for FORTRAN style column-major array
Example
import numpy as np
x = np.empty([3,2], dtype = int)
print x
[[22649312 1701344351]
[1818321759 1885959276]
[16779776 156368896]]
Note − The elements in an array show random values as they are
not initialized.
numpy.zeros
Returns a new array of specified size, filled with zeros.
1 Shape
Shape of an empty array in int or sequence of int
2 Dtype
Desired output data type. Optional
3 Order
'C' for C-style row-major array, 'F' for FORTRAN style column-major array
Example 1
# array of five zeros. Default dtype is float
import numpy as np
x = np.zeros(5)
print x
[ 0. 0. 0. 0. 0.]
Example 2
import numpy as np
x = np.zeros((5,), dtype = np.int)
print x
Example 3
# custom type
import numpy as np
x = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
print x
[[(0,0)(0,0)]
[(0,0)(0,0)]]
numpy.ones
Returns a new array of specified size and type, filled with ones.
1 Shape
Shape of an empty array in int or tuple of int
2 Dtype
Desired output data type. Optional
3 Order
'C' for C-style row-major array, 'F' for FORTRAN style column-major array
Example 1
# array of five ones. Default dtype is float
import numpy as np
x = np.ones(5)
print x
Example 2
import numpy as np
x = np.ones([2,2], dtype = int)
print x
[[1 1]
[1 1]]
Numpy.empty
As the name specifies, The empty routine is used to create an uninitialized array of
specified shape and data type.
Example
1. import numpy as np
2. arr = np.empty((3,2), dtype = int)
3. print(arr)
Output:
[[ 140482883954664 36917984]
[ 140482883954648 140482883954648]
[6497921830368665435 172026472699604272]]
NumPy.Zeros
This routine is used to create the numpy array with the specified shape where each
numpy array item is initialized to 0.
Example
1. import numpy as np
2. arr = np.zeros((3,2), dtype = int)
3. print(arr)
Output:
[[0 0]
[0 0]
[0 0]]
NumPy.ones
This routine is used to create the numpy array with the specified shape where each
numpy array item is initialized to 1.
Example
1. import numpy as np
2. arr = np.ones((3,2), dtype = int)
3. print(arr)
Output:
[[1 1]
[1 1]
[1 1]]
numpy.arange
This function returns an ndarray object containing evenly spaced values within
a given range. The format of the function is as follows −
numpy.arange(start, stop, step, dtype)
1 start
The start of an interval. If omitted, defaults to 0
2 stop
The end of an interval (not including this number)
3 step
Spacing between values, default is 1
4 dtype
Data type of resulting ndarray. If not given, data type of input is used
The following examples show how you can use this function.
Example 1
import numpy as np
x = np.arange(5)
print x
[0 1 2 3 4]
Example 2
import numpy as np
# dtype set
x = np.arange(5, dtype = float)
print x
[0. 1. 2. 3. 4.]
Example 3
# start and stop parameters set
import numpy as np
x = np.arange(10,20,2)
print x
[10 12 14 16 18]
numpy.linspace
This function is similar to arange() function. In this function, instead of step
size, the number of evenly spaced values between the interval is specified. The
usage of this function is as follows −
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
Sr.No
Parameter & Description
.
1 start
The starting value of the sequence
2 stop
The end value of the sequence, included in the sequence if endpoint set to true
3 num
The number of evenly spaced samples to be generated. Default is 50
endpoint
4
True by default, hence the stop value is included in the sequence. If false, it is not
included
5 retstep
If true, returns samples and step between the consecutive numbers
6 dtype
Data type of output ndarray
The following examples demonstrate the use linspace function.
Example 1
import numpy as np
x = np.linspace(10,20,5)
print x
Its output would be −
Example 2
# endpoint set to false
import numpy as np
x = np.linspace(10,20, 5, endpoint = False)
print x
Example 3
# find retstep value
import numpy as np
numpy.logspace
This function returns an ndarray object that contains the numbers that are
evenly spaced on a log scale. Start and stop endpoints of the scale are indices of
the base, usually 10.
numpy.logspace(start, stop, num, endpoint, base, dtype)
Following parameters determine the output of logspace function.
Sr.No. Parameter & Description
1 start
The starting point of the sequence is basestart
2 stop
The final value of sequence is basestop
3 num
The number of values between the range. Default is 50
4 endpoint
If true, stop is the last value in the range
5 base
Base of log space, default is 10
6 dtype
Data type of output array. If not given, it depends upon other input arguments
The following examples will help you understand the logspace function.
Example 1
import numpy as np
# default base is 10
a = np.logspace(1.0, 2.0, num = 10)
print a
Example 2
# set base of log space to 2
import numpy as np
a = np.logspace(1,10,num = 10, base = 2)
print a
----------------------------------------
NumPy - Indexing & Slicing
Contents of ndarray object can be accessed and modified by indexing or slicing,
just like Python's in-built container objects.
Example
Slice elements from index 1 to index 5 from the following array:
import numpy as np
print(arr[1:5])
Note: The result includes the start index, but excludes the end index.
Example
Slice elements from index 4 to the end of the array:
import numpy as np
print(arr[4:])
Example
Slice elements from the beginning to index 4 (not included):
import numpy as np
print(arr[:4])
Negative Slicing
Use the minus operator to refer to an index from the end:
Example
Slice from the index 3 from the end to index 1 from the end:
import numpy as np
print(arr[-3:-1])
STEP
Use the step value to determine the step of the slicing:
Example
Return every other element from index 1 to index 5:
import numpy as np
print(arr[1:5:2])
Example
Return every other element from the entire array:
import numpy as np
print(arr[::2])
Slicing 2-D Arrays
Example
From the second element, slice elements from index 1 to index 4 (not included):
import numpy as np
print(arr[1, 1:4])
Example
From both elements, return index 2:
import numpy as np
print(arr[0:2, 2])
Example
From both elements, slice index 1 to index 4 (not included), this will return a 2-D array:
import numpy as np
print(arr[0:2, 1:4])
print(arr[0, 1:4])
Example 1
import numpy as np
a = np.arange(10)
s = slice(2,7,2)
print a[s]
[2 4 6]
In the above example, an ndarray object is prepared by arange() function.
Then a slice object is defined with start, stop, and step values 2, 7, and 2
respectively. When this slice object is passed to the ndarray, a part of it starting
with index 2 up to 7 with a step of 2 is sliced.
The same result can also be obtained by giving the slicing parameters separated
by a colon : (start:stop:step) directly to the ndarray object.
Example 2
import numpy as np
a = np.arange(10)
b = a[2:7:2]
print b
[2 4 6]
If only one parameter is put, a single item corresponding to the index will be
returned. If a : is inserted in front of it, all items from that index onwards will be
extracted. If two parameters (with : between them) is used, items between the
two indexes (not including the stop index) with default step one are sliced.
Example 3
# slice single item
import numpy as np
a = np.arange(10)
b = a[5]
print b
5
Example 4
# slice items starting from index
import numpy as np
a = np.arange(10)
print a[2:]
[2 3 4 5 6 7 8 9]
Example 5
# slice items between indexes
import numpy as np
a = np.arange(10)
print a[2:5]
[2 3 4]
The above description applies to multi-dimensional ndarray too.
Example 6
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print a
[[1 2 3]
[3 4 5]
[4 5 6]]
Slicing can also include ellipsis (…) to make a selection tuple of the same
length as the dimension of an array. If ellipsis is used at the row position, it will
return an ndarray comprising of items in rows.
Example 7
# array to begin with
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print a[1,...]
print '\n'
The copy owns the data and any changes made to the copy will not affect original array, and
any changes made to the original array will not affect the copy.
The view does not own the data and any changes made to the view will affect the original
array, and any changes made to the original array will affect the view.
COPY:
Example
Make a copy, change the original array, and display both arrays:
import numpy as np
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
The copy SHOULD NOT be affected by the changes made to the original array.
VIEW:
Example
Make a view, change the original array, and display both arrays:
import numpy as np
x = arr.view()
arr[0] = 42
print(arr)
print(x)
The view SHOULD be affected by the changes made to the original array.
import numpy as np
x = arr.view()
x[0] = 31
print(arr)
print(x)
The original array SHOULD be affected by the changes made to the view.
Every NumPy array has the attribute base that returns None if the array owns the data.
Example
Print the value of the base attribute to check if an array owns it's data or not:
import numpy as np
x = arr.copy()
y = arr.view()
print(x.base)
print(y.base)
Example
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
print("The array:",a)
print("The maximum elements of columns:",a.max(axis = 0))
print("The minimum element of rows",a.min(axis = 1))
print("The sum of all rows",a.sum(axis = 1))
Output:
Standard deviation means how much each element of the array varies from
the mean value of the numpy array.
Example
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
print(np.sqrt(a))
print(np.std(a))
Output:
In the following example, the arithmetic operations are performed on the two
multi-dimensional arrays a and b.
Example
1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. b = np.array([[1,2,3],[12, 19, 29]])
4. print("Sum of array a and b\n",a+b)
5. print("Product of array a and b\n",a*b)
6. print("Division of array a and b\n",a/b)
Array Concatenation
The numpy provides us with the vertical stacking and horizontal stacking
which allows us to concatenate two multi-dimensional arrays vertically or
horizontally.
Example
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
b = np.array([[1,2,3],[12, 19, 29]])
print("Arrays vertically concatenated\n",np.vstack((a,b)));
print("Arrays horizontally concatenated\n",np.hstack((a,b)))
Output:
import numpy as np
# 10 to 1 with a step of -2
a = np.arange(10, 1, -2)
Run on IDE
Output :
A sequential array with a negative step:
[10 8 6 4 2]
Example #2:
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
Output :
Elements are:
[2 4 7]
Types of Indexing
All arrays generated by basic slicing are always view of the original array.
Code #1:
# Python program for basic slicing.
import numpy as np
a = np.arange(20)
# a[start:stop:step]
Output :
Array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
To select every two elements, you can use the following slice:
[m:n:2]
In general, the following expression selects every k element
between m and n:
[m:n:k]
If k is negative, the slice returns elements in reversed order starting
from m to n+1. The following table illustrates the slicing expressions:
Slicing Expression Meaning
a[:n] Select elements starting with index 0 and up to element with index n-1
a[m:] Select elements starting with index m and up to the last element
a[m:-1] Select elements starting with index m and up to the last element
import numpy as np
a = np.arange(0, 10)
print('a=', a)
print('a[2:5]=', a[2:5])
print('a[:]=', a[:])
print('a[0:-1]=', a[0:-1])
print('a[0:6]=', a[0:6])
print('a[7:]=', a[7:])
print('a[5:-1]=', a[5:-1])
print('a[0:5:2]=', a[0:5:2])
print('a[::-1]=', a[::-1])
Output:
a= [0 1 2 3 4 5 6 7 8 9]
a[2:5]= [2 3 4]
a[:]= [0 1 2 3 4 5 6 7 8 9]
a[0:-1]= [0 1 2 3 4 5 6 7 8]
a[0:6]= [0 1 2 3 4 5]
a[7:]= [7 8 9]
a[5:-1]= [5 6 7 8]
a[0:5:2]= [0 2 4]
a[::-1]= [9 8 7 6 5 4 3 2 1 0]
Numpy array slicing on multidimensional arrays
To slice a multidimensional array, you apply the square brackets [] and
the : notation to
each dimension (or axis). The slice returns a reduced array where each
element matches the selection rules. For example:
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print(a[0:2, :])
Output:
[[1 2 3]
[4 5 6]]
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print(a[1:, 1:])
Output:
[[5 6]
[8 9]]
In the expression a[1:, 1:]:
First, 1: selects the elements starting at index 1 to the last element of the
first axis (or row), which returns:
[[4 5 6]
[7 8 9]]Code language: Python (python)
Second, 1: selects the elements startingat index 1 to the last elements of
the second axis (or column), which returns:
[[5 6]
[8 9]]
Summary
Code #2:
# Python program for basic slicing
# and indexing
import numpy as np
# A 3-Dimensional array
a = np.array([[0, 1, 2, 3, 4, 5]
Run on IDE
Output :
Array is:
[[0 1 2 3 4 5]
[6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]
a[0, 3:5] = [3 4]
a[4:, 4:] = [[28 29],
[34 35]]
a[:, 2] = [2 8 14 20 26 32]
For numpy arrays a[2:,:] will return a slice of a starting from index 2 of the
first dimension and the entirety of the second dimension. a[2::2, ::2] will
thus return only every second element compared to a[2:,:].
In your example, the returned elements are from the following indices
Ellipsis can also be used along with basic slicing. Ellipsis (…) is the number of :
objects needed to make a selection tuple of the same length as the
dimensions of the array.
# Python program for indexing using
import numpy as np
# A 3 dimensional array.
Print(b)
Run on IDE
Output :
[[ 2 5]
[ 8 11]]
Test
Two-dimensional array
In this type of array, elements are stored in rows and columns which represent a matrix.
Three-dimensional array
When slicing an array, you pass the starting index and the ending index which are
separated by a full colon. You use the square brackets as shown below.
arr[start:end]
Note: The result above includes the start index and excludes the end index.
Negative slicing
The minus operator is used to refer to an index from the end of an array; you slice an
array from the end instead of from the start.
Example: Slice from index 4 (from the end) to index 2 (from the end).
To slice a 2-D array in NumPy, you have to specify row index and column index which
are separated using a comma as shown below.
arr[1, 1:4]
The part before the comma represents the row while the part after the comma
represents the column.
Array indexing refers to accessing an array element using an index number that starts
from 0. The difference between indexing and slicing is that with the former, you simply
access the element. With slicing, you extract specific elements from the array.
You need to pass the index of that element as shown below, to access the 1-D array.
To access the 2-D array, you need to use commas to separate the integers which
represent the dimension and the index of the element. The first integer represents the
row and the other represents the column.