KEMBAR78
3.2 NumPy Arrays | PDF | Parameter (Computer Programming) | Integer (Computer Science)
0% found this document useful (0 votes)
19 views74 pages

3.2 NumPy Arrays

The document provides an overview of creating and manipulating NumPy ndarray objects, which are n-dimensional arrays that store similar types of elements. It explains how to create ndarrays using the array() function, access elements using indexing, and explore different dimensions (0-D, 1-D, 2-D, and 3-D). Additionally, it covers attributes like ndim and shape, as well as reshaping arrays and changing data types.

Uploaded by

Rajesh B.M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views74 pages

3.2 NumPy Arrays

The document provides an overview of creating and manipulating NumPy ndarray objects, which are n-dimensional arrays that store similar types of elements. It explains how to create ndarrays using the array() function, access elements using indexing, and explore different dimensions (0-D, 1-D, 2-D, and 3-D). Additionally, it covers attributes like ndim and shape, as well as reshaping arrays and changing data types.

Uploaded by

Rajesh B.M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 74

NumPy Creating Arrays

Create a NumPy ndarray Object


NumPy is used to work with arrays. The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() function.

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.

Creating a ndarray object


The ndarray object can be created by using the array routine of the numpy module. For
this purpose, we need to import the numpy.

1. >>> a = numpy.array

Example
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

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

arr = np.array((1, 2, 3, 4, 5))

print(arr)

Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).

nested array: are arrays that have arrays as their elements.

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.

These are the most common and basic arrays.


Example
Create a 1-D array containing the values 1,2,3,4,5:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.

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

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)

3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.

These are often used to represent a 3rd order tensor.

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

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(arr)

Check Number of Dimensions?


NumPy Arrays provides the ndim attribute that returns an integer that tells us how many
dimensions the array have.

Example
Check how many dimensions the arrays have:

import numpy as np

a = np.array(42)

b = np.array([1, 2, 3, 4, 5])

c = np.array([[1, 2, 3], [4, 5, 6]])

d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

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

arr = np.array([1, 2, 3, 4], ndmin=5)

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)

The parameters are described in the following table.

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.

3 copy It is optional. By default, it is true which means the object is copied.

4 order There can be 3 possible values assigned to this option. It can be C


(column order), R (row order), or A (any)

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.

6 ndmin It represents the minimum dimensions of the resultant array.

To create an array using the list, use the following syntax.

1. >>> a = numpy.array([1, 2, 3])

To create a multi-dimensional array object, use the following syntax.


1. >>> a = numpy.array([[1, 2, 3], [4, 5, 6]])

To change the data type of the array elements, mention the name of the data type along
with the collection.

1. >>> a = numpy.array([1, 3, 5, 7], complex)

Finding the dimensions of the Array


The ndim function can be used to find the dimensions of the array.

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.

Consider the following example.

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:

Each item contains 8 bytes.

Finding the data type of each array item


To check the data type of each array item, the dtype function is used. Consider the
following example to check the data type of the array items.

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:

Each item is of the type int64

------------------------------------------------------------

NumPy Array Indexing


Access Array Elements
Array indexing is the same as accessing an array element.

You can access an array element by referring to its index number.

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

arr = np.array([1, 2, 3, 4])

print(arr[0])

Example
Get the second element from the following array.

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[1])
Example
Get third and fourth elements from the following array and add them.

import numpy as np

arr = np.array([1, 2, 3, 4])

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]])

print('2nd element on 1st row: ', arr[0, 1])

Example
Access the element on the 2nd row, 5th column:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('5th element on 2nd row: ', arr[1, 4])


Access 3-D Arrays
To access elements from 3-D arrays we can use comma separated integers representing the
dimensions and the index of the element.

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.

And this is why:

The first number represents the first dimension, which contains two arrays:

[[1, 2, 3], [4, 5, 6]]

and:
[[7, 8, 9], [10, 11, 12]]

Since we selected 0, we are left with the first array:

[[1, 2, 3], [4, 5, 6]]

The second number represents the second dimension, which also contains two arrays:
[1, 2, 3]
and:
[4, 5, 6]

Since we selected 1, we are left with the second array:


[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]

[180 181 122]]]

122

Process finished with exit code 0


Negative Indexing
Use negative indexing to access an array from the end.

Example
Print the last element from the 2nd dim:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('Last element from 2nd dim: ', arr[1, -1])

Test NumPy - Ndarray Object

The most important object defined in NumPy is an N-dimensional array type


called ndarray. It describes the collection of items of the same type. Items in
the collection can be accessed using a zero-based index.
Every item in an ndarray takes the same size of block in the memory. Each
element in ndarray is an object of data-type object (called dtype).

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

The above constructor takes the following parameters −

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

Take a look at the following examples to understand better.

Example 1
import numpy as np
a = np.array([1,2,3])
print a

The output is as follows −

[1, 2, 3]

Example 2
# more than one dimensions
import numpy as np
a = np.array([[1, 2], [3, 4]])
print a
print(a.

The output is as follows −

[[1, 2]
[3, 4]]

Example 3
# minimum dimensions
import numpy as np
a = np.array([1, 2, 3,4,5], ndmin = 2)
print(a)

The output is as follows −

[[1, 2, 3, 4, 5]]

Example 4
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print a

The output is as follows −

[ 1.+0.j, 2.+0.j, 3.+0.j]


The ndarray object consists of contiguous one-dimensional segment of
computer memory, combined with an indexing scheme that maps each item to a
location in the memory block. The memory block holds the elements in a row-
major order (C style) or a column-major order (FORTRAN or MatLab style).

Finding the shape and size of the array

NumPy Array Shape


Shape of an Array
The shape of an array is the number of elements in each dimension.

Get the Shape of an Array


NumPy arrays have an attribute called shape that returns a tuple with each index having the
number of corresponding elements.

Example
Print the shape of a 2-D array:

import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

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.

Consider the following example.


Example
import numpy as np
a = np.array([[1,2,3,4,5,6,7]])
print("Array Size:",a.size)
print("Shape:",a.shape)

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

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('shape of array :', arr.shape)

What does the shape tuple represent?


Integers at every index tells about the number of elements the corresponding dimension has.

In the example above at index-4 we have value 4, so we can say that 5th ( 4 + 1 th)
dimension has 4 elements.

NumPy Array Reshaping

Reshaping arrays
Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.


By reshaping we can add or remove dimensions or change number of elements in each
dimension.

Reshaping the array objects


By the shape of the array, we mean the number of rows and columns of a multi-
dimensional array. However, the numpy module provides us the way to reshape the array
by changing the number of rows and columns of the multi-dimensional 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.

Let's reshape the array given in the following image.

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:

printing the original array..


[[1 2]
[3 4]
[5 6]]
printing the reshaped array..
[[1 2 3]
[4 5 6]]

Reshape From 1-D to 2-D


Example
Convert the following 1-D array with 12 elements into a 2-D array.

The outermost dimension will have 4 arrays, each with 3 elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(4, 3)

print(newarr)

Reshape From 1-D to 3-D


Example
Convert the following 1-D array with 12 elements into a 3-D array.

The outermost dimension will have 2 arrays that contains 3 arrays, each with 2 elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(2, 3, 2)

print(newarr)

Can We Reshape Into any Shape?


Yes, as long as the elements required for reshaping are equal in both shapes.
We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we cannot
reshape it into a 3 elements 3 rows 2D array as that would require 3x3 = 9 elements.

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

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

newarr = arr.reshape(3, 3)

print(newarr)

Returns Copy or View?


Example
Check if the returned array is a copy or a view:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

print(arr.reshape(2, 4).base)

The example above returns the original array, so it is a view.

------------------------------------------------------------------------------

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

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

newarr = arr.reshape(2, 2, -1)

print(newarr)

Note: We can not pass -1 to more than one dimension.

-----------------------------------------------------

Flattening the arrays


Flattening array means converting a multidimensional array into a 1D array.

We can use reshape(-1) to do this.

Example
Convert the array into a 1D array:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

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

a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])

print(a)

#flatten the array

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]

Slicing in the Array


Slicing in the NumPy array is the way to extract a range of elements from an array.
Slicing in the array is performed in the same way as it is performed in the python list.

Consider the following example to print a particular element of the array.

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:

[ 5. 6.11111111 7.22222222 8.33333333 9.44444444 10.55555556


11.66666667 12.77777778 13.88888889 15. ]

Finding the maximum, minimum, and sum of the array


elements
The NumPy provides the max(), min(), and sum() functions which are used to find the
maximum, minimum, and sum of the array elements respectively.

Consider the following example.

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

NumPy - Data Types


NumPy supports a much greater variety of numerical types than Python does.
The following table shows different scalar data types defined in NumPy.

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.

Data Type Objects (dtype)

A data type object describes interpretation of fixed block of memory


corresponding to an array, depending on the following aspects −

 Type of data (integer, float or Python object)


 Size of data
 Byte order (little-endian or big-endian)
 In case of structured type, the names of fields, data type of each field and
part of the memory block taken by each field.
 If data type is a subarray, its shape and data type

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).

A dtype object is constructed using the following syntax −

numpy.dtype(object, align, copy)

The parameters are −

 Object − To be converted to data type object


 Align − If true, adds padding to the field to make it similar to C-struct
 Copy − Makes a new copy of dtype object. If false, the result is reference
to builtin data type object
Example 1
# using array-scalar type
import numpy as np
dt = np.dtype(np.int32)
print dt

The output is as follows −

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

The output is as follows −

>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

The output is as follows −

[('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

The output is as follows −

[(10,) (20,) (30,)]


Example 6
# file name can be used to access content of age column
import numpy as np

dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype = dt)
print a['age']

The output is as follows −

[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

The output is as follows −

[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])

Example 8
import numpy as np

student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])


a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
print a

The output is as follows −

[('abc', 21, 50.0), ('xyz', 18, 75.0)]

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.

We can create a dtype object by using the following syntax.

1. numpy.dtype(object, align, copy)

The constructor accepts the following object.

Object: It represents the object which is to be converted to the data type.

Align: It can be set to any boolean value. If true, then it adds extra padding to make it
equivalent to a C struct.

Copy: It creates another copy of the dtype object.

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

Checking the Data Type of an Array


The NumPy array object has a property called dtype that returns the data type of the array:

Example
Get the data type of an array object:

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr.dtype)

Example
Get the data type of an array containing strings:

import numpy as np

arr = np.array(['apple', 'banana', 'cherry'])

print(arr.dtype)

Creating Arrays With a Defined Data Type


We use the array() function to create arrays, this function can take an optional
argument: dtype that allows us to define the expected data type of the array elements:

Example
Create an array with data type string:
import numpy as np

arr = np.array([1, 2, 3, 11], dtype='S')

print(arr)
print(arr.dtype)

For i, u, f, S and U we can define size as well.

Example
Create an array with data type 4 bytes integer:

import numpy as np

arr = np.array([1, 2, 3, 4], dtype='i4')

print(arr)
print(arr.dtype)

What if a Value Can Not Be Converted?


If a type is given in which elements can't be casted then NumPy will raise a ValueError.

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

arr = np.array(['a', '2', '3'], dtype='i')


Converting Data Type on Existing Arrays
The best way to change the data type of an existing array, is to make a copy of the array with
the astype() method.

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

arr = np.array([1.1, 2.1, 3.1])

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

arr = np.array([1.1, 2.1, 3.1])

newarr = arr.astype(int)

print(newarr)
print(newarr.dtype)

Example
Change data type from integer to boolean:
import numpy as np

arr = np.array([1, 0, 3])

newarr = arr.astype(bool)

print(newarr)
print(newarr.dtype)

Creating a Structured data type


We can create a map-like (dictionary) data type which contains the mapping between the
values. For example, it can contain the mapping between employees and salaries or the
students and the age, etc.

Consider the following example.

Example 1
import numpy as np
d = np.dtype([('salary',np.float)])
print(d)

Output:

[('salary', '<="" pre="">

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:

[(10000.12,) (20000.5 ,)]

NumPy - Array Attributes


we will discuss the various array attributes of NumPy.
ndarray.shape

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

The output is as follows −

(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

The output is as follows −

[[1, 2]
[3, 4]
[5, 6]]
-----------------------------------------------------------------------------------------------------------

Example 3

NumPy also provides a reshape function to resize an array.

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

This array attribute returns the number of array dimensions.

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:

# Python Programming illustrating

# numpy.arange method

import numpy as np

print("A\n", np.arange(4),"\n")
print("A\n", np.arange(4).reshape(2, 2), "\n")

print("A\n", np.arange(4, 10), "\n")

print("A\n", np.arange(4, 20, 3), "\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

# Python Programming illustrating

# numpy.arange method

import numpy as np

# Printing all numbers from 1 to


# 2 in steps of 0.1

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

The output is as follows −

[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

The output is as follows −

[[[ 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

The output is as follows −

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

The output is as follows −

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

The following example shows the current values of flags.

import numpy as np
x = np.array([1,2,3,4,5])
print x.flags

The output is as follows −

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

It creates an uninitialized array of specified shape and dtype. It uses the


following constructor −

numpy.empty(shape, dtype = float, order = 'C')

The constructor takes the following parameters.

Sr.No. Parameter & Description

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

The following code shows an example of an empty array.

import numpy as np
x = np.empty([3,2], dtype = int)
print x

The output is as follows −

[[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.

numpy.zeros(shape, dtype = float, order = 'C')

The constructor takes the following parameters.

Sr.No. Parameter & Description

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

The output is as follows −

[ 0. 0. 0. 0. 0.]

Example 2
import numpy as np
x = np.zeros((5,), dtype = np.int)
print x

Now, the output would be as follows −


[0 0 0 0 0]

Example 3
# custom type
import numpy as np
x = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
print x

It should produce the following output −

[[(0,0)(0,0)]
[(0,0)(0,0)]]

numpy.ones
Returns a new array of specified size and type, filled with ones.

numpy.ones(shape, dtype = None, order = 'C')

The constructor takes the following parameters.

Sr.No. Parameter & Description

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

The output is as follows −


[ 1. 1. 1. 1. 1.]

Example 2
import numpy as np
x = np.ones([2,2], dtype = int)
print x

Now, the output would be as follows −

[[1 1]
[1 1]]

Numpy Array Creation


The ndarray object can be constructed by using the following routines.

Numpy.empty
As the name specifies, The empty routine is used to create an uninitialized array of
specified shape and data type.

The syntax is given below.

1. numpy.empty(shape, dtype = float, order = 'C')

It accepts the following parameters.

o Shape: The desired shape of the specified array.


o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.

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.

The syntax is given below.

1. numpy.zeros(shape, dtype = float, order = 'C')

It accepts the following parameters.

o Shape: The desired shape of the specified array.


o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.

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.

The syntax to use this module is given below.

1. numpy.ones(shape, dtype = none, order = 'C')

It accepts the following parameters.


o Shape: The desired shape of the specified array.
o dtype: The data type of the array items.
o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.

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 - Array From Numerical Ranges


In this chapter, we will see how to create an array from numerical ranges.

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)

The constructor takes the following parameters.

Sr.No. Parameter & Description

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

Its output would be as follows −

[0 1 2 3 4]

Example 2
import numpy as np
# dtype set
x = np.arange(5, dtype = float)
print x

Here, the output would be −

[0. 1. 2. 3. 4.]

Example 3
# start and stop parameters set
import numpy as np
x = np.arange(10,20,2)
print x

Its output is as follows −

[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)

The constructor takes the following parameters.

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 −

[10. 12.5 15. 17.5 20.]

Example 2
# endpoint set to false
import numpy as np
x = np.linspace(10,20, 5, endpoint = False)
print x

The output would be −

[10. 12. 14. 16. 18.]

Example 3
# find retstep value
import numpy as np

x = np.linspace(1,2,5, retstep = True)


print x
# retstep here is 0.25

Now, the output would be −

(array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)

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

Its output would be as follows −

[ 10. 12.91549665 16.68100537 21.5443469 27.82559402


35.93813664 46.41588834 59.94842503 77.42636827 100. ]

Example 2
# set base of log space to 2
import numpy as np
a = np.logspace(1,10,num = 10, base = 2)
print a

Now, the output would be −

[ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.]

----------------------------------------
NumPy - Indexing & Slicing
Contents of ndarray object can be accessed and modified by indexing or slicing,
just like Python's in-built container objects.

items in ndarray object follows zero-based index. Three types of indexing


methods are available − field access, basic slicing and advanced indexing.
Basic slicing is an extension of Python's basic concept of slicing to n
dimensions. A Python slice object is constructed by giving start, stop,
and step parameters to the built-in slice function. This slice object is passed to
the array to extract a part of array.

NumPy Array Slicing


Slicing arrays
Slicing in python means taking elements from one given index to another given index.

We pass slice instead of index like this: [start:end].

We can also define the step, like this: [start:end:step].

If we don't pass start its considered 0


If we don't pass end its considered length of array in that dimension

If we don't pass step its considered 1

Example
Slice elements from index 1 to index 5 from the following array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

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

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[4:])

Example
Slice elements from the beginning to index 4 (not included):

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

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

arr = np.array([1, 2, 3, 4, 5, 6, 7])

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

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5:2])

Example
Return every other element from the entire array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

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

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[1, 1:4])

Note: Remember that second element has index 1.

Example
From both elements, return index 2:

import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

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

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

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]

Its output is as follows −

[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

Here, we will get the same output −

[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

Its output is as follows −

5
Example 4
# slice items starting from index
import numpy as np
a = np.arange(10)
print a[2:]

Now, the output would be −

[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]

Here, the output would be −

[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

# slice items starting from index


print 'Now we will slice the array from the index a[1:]'
print a[1:]

The output is as follows −

[[1 2 3]
[3 4 5]
[4 5 6]]

Now we will slice the array from the index a[1:]


[[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 'Our array is:'


print a
print '\n'

# this returns array of items in the second column


print 'The items in the second column are:'
print a[...,1]
print '\n'

# Now we will slice all items from the second row


print 'The items in the second row are:'

print a[1,...]
print '\n'

# Now we will slice all items from column 1 onwards


print 'The items column 1 onwards are:'
print a[...,1:]
The output of this program is as follows −

Our array is:


[[1 2 3]
[3 4 5]
[4 5 6]]
The items in the second column are:
[2 4 5]

The items in the second row are:


[3 4 5]
The items column 1 onwards are:
[[2 3]
[4 5]
[5 6]]

NumPy Array Copy vs View


The Difference Between Copy and View
The main difference between a copy and a view of an array is that the copy is a new array,
and the view is just a view of the original array.

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

arr = np.array([1, 2, 3, 4, 5])

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

arr = np.array([1, 2, 3, 4, 5])

x = arr.view()

arr[0] = 42

print(arr)
print(x)

The view SHOULD be affected by the changes made to the original array.

Make Changes in the VIEW:


Example
Make a view, change the view, and display both arrays:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

x = arr.view()
x[0] = 31

print(arr)
print(x)

The original array SHOULD be affected by the changes made to the view.

Check if Array Owns its Data


As mentioned above, copies owns the data, and views does not own the data, but how can we
check this?

Every NumPy array has the attribute base that returns None if the array owns the data.

Otherwise, the base attribute refers to the original object.

Example
Print the value of the base attribute to check if an array owns it's data or not:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

x = arr.copy()

y = arr.view()

print(x.base)
print(y.base)

The copy returns None.


The view returns the original array.

NumPy Array Axis


A NumPy multi-dimensional array is represented by the axis where axis-0
represents the columns and axis-1 represents the rows. We can mention the
axis to perform row-level or column-level calculations like the addition of row
or column elements.

To calculate the maximum element among each column, the minimum


element among each row, and the addition of all the row elements, consider
the following example.

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:

The array: [[1 2


30]
[10 15 4]]
The maximum elements of columns: [10 15 30]
The minimum element of rows [1 4]
The sum of all rows [33 29]
---------------------------------------------------------------------

Finding square root and standard deviation


The sqrt() and std() functions associated with the numpy array are used to
find the square root and standard deviation of the array elements
respectively.

Standard deviation means how much each element of the array varies from
the mean value of the numpy array.

Consider the following example.

Example
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
print(np.sqrt(a))
print(np.std(a))

Output:

[[1. 1.41421356 5.47722558]


[3.16227766 3.87298335 2. ]]
10.044346115546242

Arithmetic operations on the array


The numpy module allows us to perform the arithmetic operations on multi-
dimensional arrays directly.

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.

Consider the following example.

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:

Arrays vertically concatenated


[[ 1 2 30]
[10 15 4]
[ 1 2 3]
[12 19 29]]
Arrays horizontally concatenated
[[ 1 2 30 1 2 3]
[10 15 4 12 19 29]]

Indexing using index arrays

Indexing can be done in numpy by using an array as an index. In case of slice,


a view or shallow copy of the array is returned but in index array a copy of the
original array is returned. Numpy arrays can be indexed with other arrays or
any other sequence with the exception of tuples. The last element is indexed
by -1 second last by -2 and so on.
Example #1:
# Python program to demonstrate
# the use of index arrays.

import numpy as np

# Create a sequence of integers from

# 10 to 1 with a step of -2

a = np.arange(10, 1, -2)

print("\n A sequential array with a negative step: \n",a)

# Indexes are specified inside the np.array method.

newarr = a[np.array([3, 1, 2 ])]

print("\n Elements at these indices are:\n",newarr)

Run on IDE

Output :
A sequential array with a negative step:
[10 8 6 4 2]

Elements at these indices are:


[4 8 6]

Example #2:
import numpy as np

# NumPy array with elements from 1 to 9

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

# Index values can be negative.

arr = x[np.array([1, 3, -3])]

print("\n Elements are : \n",arr)

Output :
Elements are:
[2 4 7]
Types of Indexing

There are two types of indexing :


Basic Slicing and indexing : Consider the syntax x[obj] where x is the array
and obj is the index. Slice object is the index in case of basic slicing. Basic
slicing occurs when obj is :
 a slice object that is of the form start : stop : step
 an integer
 or a tuple of slice objects and integers

All arrays generated by basic slicing are always view of the original array.
Code #1:
# Python program for basic slicing.

import numpy as np

# Arrange elements from 0 to 19

a = np.arange(20)

print("\n Array is:\n ",a)

# a[start:stop:step]

print("\n a[-8:17:1] = ",a[-8:17:1])

# The : operator means all elements till the end.

print("\n a[10:] = ",a[10:])

Output :
Array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]

a[-8:17:1] = [12 13 14 15 16]

a[10:] = [10 11 12 13 14 15 16 17 18 19]


Numpy array slicing on on-dimensional arrays
NumPy arrays use brackets [] and : notations for slicing like lists. By using
slices, you can select a range of elements in an array with the following
syntax:
[m:n]Code language: Python (python)
This slice selects elements starting with m and ending with n-1. Note that the
nth element
is not included. In fact, the slice m:n can be explicitly defined as:
[m:n:1]
The number 1 specifies that the slice selects every element
between m and n.

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[m:n] Select elements with an index starting at m and ending at n-1.

a[:] or a[0:-1] Select all elements in a given axis

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

a[m:n:k] Select elements with index m through n (exclusive), with an increment k

a[::-1] Select all elements in reverse order

See the following example:

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]]

In this example, array a is a 2-D array. In the expression a[0:2, :]:


First, the 0:2 selects the element at index 0 and 1, not 2 that returns:
[[1 2 3]
[4 5 6]]
Then, the : select all elements. Therefore the whole expression returns:
[[1 2 3]
[4 5 6]]

Consider another example:

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

 Use slicing to extract elements from a numpy array


 Use a[m:n:p] to slice one-dimensional arrays.
 Use a[m:n:p, i:j:k, ...] to slice multidimensional arrays

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]

[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]]

print("\n Array is:\n ",a)

# slicing and indexing

print("\n a[0, 3:5] = ",a[0, 3:5])

print("\n a[4:, 4:] = ",a[4:, 4:])

print("\n a[:, 2] = ",a[:, 2])

print("\n a[2:;2, ::2] = ",a[2:;2, ::2])

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]

a[2:;2, ::2] = [[12 14 16],


[24 26 28]]
The figure below makes the concept more clear:

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

[[(2,0), (2,2), (2,4)], [(4,0), (4,2), (4,4)]]

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

# basic slicing with ellipsis

import numpy as np
# A 3 dimensional array.

b = np.array([[[1, 2, 3],[4, 5, 6]],

[[7, 8, 9],[10, 11, 12]]])

Print(b)

print(b[...,1]) #Equivalent to b[: ,: ,1 ]

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

This type of array comprises 2-D matrices as its elements.

Slicing 1-D arrays

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]

arr is the variable name of the array.

Here’s an example for better understanding:


The starting index is 1 and the ending index is 5. Therefore, you will slice from the
second element since indexing in the array starts from 0 up to the fourth element.

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).

Slicing 2-D arrays

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.

Example: Slice elements from index 1 to 4 from the second row.


The last index is excluded.

NumPy array indexing

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.

NumPy 1-D array indexing

You need to pass the index of that element as shown below, to access the 1-D array.

The output shows 10 is at index 0.

NumPy 2-D array indexing

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.

You might also like