0% found this document useful (0 votes)
4 views23 pages

Numpy in Python

The document provides an overview of NumPy, focusing on creating and manipulating ndarray objects, including different dimensions of arrays (0-D, 1-D, 2-D, and 3-D) and how to access their elements. It explains array indexing, slicing, and the various data types available in NumPy, along with examples for each concept. Additionally, it covers how to check the data type of a NumPy array using the dtype attribute.

Uploaded by

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

Numpy in Python

The document provides an overview of NumPy, focusing on creating and manipulating ndarray objects, including different dimensions of arrays (0-D, 1-D, 2-D, and 3-D) and how to access their elements. It explains array indexing, slicing, and the various data types available in NumPy, along with examples for each concept. Additionally, it covers how to check the data type of a NumPy array using the dtype attribute.

Uploaded by

poonam.sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),

MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

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.

import numpy as np
[1 2 3 4 5]
arr = [Link]([1, 2, 3, 4, 5]) <class '[Link]'>

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 [Link] 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 = [Link]((1, 2, 3, 4, 5))

print(arr)

OUTPUT
[1 2 3 4 5]

1|Page
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

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 = [Link](42)

print(arr)

OUTPUT
42

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 = [Link]([1, 2, 3, 4, 5])

2|Page
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

print(arr)

OUTPUT

[1 2 3 4 5]

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

Example

Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

import numpy as np

arr = [Link]([[1, 2, 3], [4, 5, 6]])

print(arr)

OUTPUT
[[1 2 3]
[4 5 6]]
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:

3|Page
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

import numpy as np

arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(arr)

OUTPUT

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

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

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 = [Link](42)
b = [Link]([1, 2, 3, 4, 5])
c = [Link]([[1, 2, 3], [4, 5, 6]])
d = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print([Link])
print([Link])
print([Link])
print([Link])

OUTPUT
0
1
2
3
4|Page
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

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 = [Link]([1, 2, 3, 4])

print(arr[0])

OUTPUT
1
Example

Get the second element from the following array.

import numpy as np

arr = [Link]([1, 2, 3, 4])

print(arr[1])

OUTPUT
2

Get third and fourth elements from the following array and add them.

5|Page
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

import numpy as np

arr = [Link]([1, 2, 3, 4])

print(arr[2] + arr[3])

OUTPUT
7

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 = [Link]([[1,2,3,4,5], [6,7,8,9,10]])

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

OUTPUT
2nd element on 1st dim: 2

Example

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

import numpy as np

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

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

6|Page
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

OUTPUT
5th element on 2nd dim: 10

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 = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(arr[0, 1, 2])

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

7|Page
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

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

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 = [Link]([[1,2,3,4,5], [6,7,8,9,10]])

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

OUTPUT
Last element from 2nd dim: 10

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

8|Page
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

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 = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5])

OUTPUT

[2 3 4 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 = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[4:])

OUTPUT
[5 6 7]
Example

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

import numpy as np

arr = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[:4])

9|Page
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

OUTPUT
[1 2 3 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 = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[-3:-1])

OUTPUT
[5 6]

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 = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5:2])

OUTPUT
[2 4]
Example

Return every other element from the entire array:


10 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

import numpy as np

arr = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[::2])
OUTPUT
[1 3 5 7]

Slicing 2-D Arrays


Example

From the second element, slice elements from index 1 to index 4 (not included):

import numpy as np

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

print(arr[1, 1:4])

OUTPUT
[7 8 9]

Note: Remember that second element has index 1.

Example

From both elements, return index 2:

import numpy as np

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

print(arr[0:2, 2])

OUTPUT
[3 8]

11 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

Example

From both elements, slice index 1 to index 4 (not included), this will return a 2-D array:

import numpy as np

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

print(arr[0:2, 1:4])
OUTPUT
[[2 3 4]
[7 8 9]]

Data Types in Python

By default Python have these data types:

• strings - used to represent text data, the text is given under quote marks. e.g. "ABCD"
• integer - used to represent integer numbers. e.g. -1, -2, -3
• float - used to represent real numbers. e.g. 1.2, 42.42
• boolean - used to represent True or False.
• complex - used to represent complex numbers. e.g. 1.0 + 2.0j, 1.5 + 2.5j

NumPy Data Types

NumPy offers a wider range of numerical data types than what is available in Python. Here's the list
of most commonly used numeric data types in NumPy:

1. int8, int16, int32, int64 - signed integer types with different bit sizes
2. uint8, uint16, uint32, uint64 - unsigned integer types with different bit sizes
3. float32, float64 - floating-point types with different precision levels
4. complex64, complex128 - complex number types with different precision levels

12 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

Check Data Type of a NumPy Array

To check the data type of a NumPy array, we can use the dtype attribute. For example,
import numpy as np

# create an array of integers


array1 = [Link]([2, 4, 6])

# check the data type of array1


print([Link])

# Output: int64
In the above example, we have used the dtype attribute to check the data type of the array1 array.
Since array1 is an array of integers, the data type of array1 is inferred as int64 by default.

Example: Check Data Type of NumPy Array

import numpy as np

# create an array of integers


int_array = [Link]([-3, -1, 0, 1])

# create an array of floating-point numbers


float_array = [Link]([0.1, 0.2, 0.3])

# create an array of complex numbers


complex_array = [Link]([1+2j, 2+3j, 3+4j])

# check the data type of int_array


print(int_array.dtype) # prints int64

13 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

# check the data type of float_array


print(float_array.dtype) # prints float64

# check the data type of complex_array


print(complex_array.dtype) # prints complex128
Output

int64
float64
complex128

Here, we have created types of arrays and checked the default data types of these arrays using
the dtype attribute.
• int_array - contains four integer elements whose default data type is int64
• float_array - contains three floating-point numbers whose default data type is float64
• complex_array - contains three complex numbers whose default data type is complex128

Creating NumPy Arrays With a Defined Data Type

In NumPy, we can create an array with a defined data type by passing the dtype parameter while
calling the [Link]() function. For example,
import numpy as np

# create an array of 32-bit integers


array1 = [Link]([1, 3, 7], dtype='int32')

print(array1, [Link])
Output

14 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

[1 3 7] int32

In the above example, we have created a NumPy array named array1 with a defined data type.
Notice the code,

[Link]([1, 3, 7], dtype='int32')

Here, inside [Link](), we have passed an array [1, 3, 7] and set the dtype parameter to int32.
Since we have set the data type of the array to int32, each element of the array is represented as a
32-bit integer.

Example: Creating NumPy Arrays With a Defined Data Type

import numpy as np

# create an array of 8-bit integers


array1 = [Link]([1, 3, 7], dtype='int8')

# create an array of unsigned 16-bit integers


array2 = [Link]([2, 4, 6], dtype='uint16')

# create an array of 32-bit floating-point numbers


array3 = [Link]([1.2, 2.3, 3.4], dtype='float32')

# create an array of 64-bit complex numbers


array4 = [Link]([1+2j, 2+3j, 3+4j], dtype='complex64')

# print the arrays and their data types


print(array1, [Link])

15 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

print(array2, [Link])
print(array3, [Link])
print(array4, [Link])
Output

[1 3 7] int8
[2 4 6] uint16
[1.2 2.3 3.4] float32
[1.+2.j 2.+3.j 3.+4.j] complex64

NumPy Type Conversion

In NumPy, we can convert the data type of an array using the astype() method. For example,
import numpy as np

# create an array of integers


int_array = [Link]([1, 3, 5, 7])

# convert data type of int_array to float


float_array = int_array.astype('float')

# print the arrays and their data types


print(int_array, int_array.dtype)
print(float_array, float_array.dtype)
Output

[1 3 5 7] int64
[1. 3. 5. 7.] float64

16 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

Here, int_array.astype('float') converts the data type


of int_array from int64 to float64 using astype().

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 = [Link](['a', '2', '3'], dtype='i')

OUTPUT
Traceback (most recent call last):
File "./[Link]", line 3, in
ValueError: invalid literal for int() with base 10: 'a'
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:

17 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

import numpy as np

arr = [Link]([1.1, 2.1, 3.1])

newarr = [Link]('i')

print(newarr)
print([Link])
OUTPUT
[1 2 3]
int32

Example

Change data type from float to integer by using int as parameter value:

import numpy as np

arr = [Link]([1.1, 2.1, 3.1])

newarr = [Link](int)

print(newarr)
print([Link])
OUTPUT
[1 2 3]
int64

NumPy Array Attributes


In NumPy, attributes are properties of NumPy arrays that provide information about the array's
shape, size, data type, dimension, and so on.

For example, to get the dimension of an array, we can use the ndim attribute.

There are numerous attributes available in NumPy, which we'll learn below.

Common NumPy Attributes


Here are some of the commonly used NumPy attributes:
Attributes Description

18 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

ndim returns number of dimension of the array

size returns number of elements in the array

dtype returns data type of elements in the array

shape returns the size of the array in each dimension.

itemsize returns the size (in bytes) of each elements in the array

data returns the buffer containing actual elements of the array in memory

To access the Numpy attributes, we use the . notation. For example,

[Link]

This returns the number of dimensions in array1.

Numpy Array ndim Attribute

The ndim attribute returns the number of dimensions in the numpy array. For example,
import numpy as np

# create a 2-D array


array1 = [Link]([[2, 4, 6],
[1, 3, 5]])

# check the dimension of array1


print([Link])

19 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

# Output: 2
In this example, [Link] returns the number of dimensions present in array1. As array1 is a 2D
array, we got 2 as an output.

NumPy Array size Attribute

The size attribute returns the total number of elements in the given array.
Let's see an example.

import numpy as np

array1 = [Link]([[1, 2, 3],


[6, 7, 8]])

# return total number of elements in array1


print([Link])

# Output: 6
In this example, [Link] returns the total number of elements in the array1 array, regardless of
the number of dimensions.
Since these are a total of 6 elements in array1, the size attribute returns 6.

20 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

NumPy Array shape Attribute

In NumPy, the shape attribute returns a tuple of integers that gives the size of the array in each
dimension. For example,
import numpy as np

array1 = [Link]([[1, 2, 3],


[6, 7, 8]])

# return a tuple that gives size of array in each dimension


print([Link])

# Output: (2,3)
Here, array1 is a 2-D array that has 2 rows and 3 columns. So [Link] returns the tuple (2,3) as
an output.

NumPy Array dtype Attribute

We can use the dtype attribute to check the datatype of a NumPy array. For example,
import numpy as np

# create an array of integers


array1 = [Link]([6, 7, 8])

# check the data type of array1


print([Link])

# Output: int64
In the above example, the dtype attribute returns the data type of array1.

21 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

Since array1 is an array of integers, the data type of array1 is inferred as int64 by default.

NumPy Array itemsize Attribute

In NumPy, the itemsize attribute determines size (in bytes) of each element in the array. For
example,
import numpy as np

# create a default 1-D array of integers


array1 = [Link]([6, 7, 8, 10, 13])

# create a 1-D array of 32-bit integers


array2 = [Link]([6, 7, 8, 10, 13], dtype=np.int32)

# use of itemsize to determine size of each array element of array1 and array2
print([Link]) # prints 8
print([Link]) # prints 4
Output

8
4

Here,

• array1 is an array containing 64-bit integers by default, which uses 8 bytes of memory per
element. So, itemsize returns 8 as the size of each element.
• array2 is an array of 32-bit integers, so each element in this array uses only 4 bytes of
memory. So, itemsize returns 4 as the size of each element.

NumPy Array data Attribute

In NumPy, we can get a buffer containing actual elements of the array in memory using
the data attribute.
22 | P a g e
MAHARISHI MARKANDESHWAR (DEEMED TO BE UNIVERSITY),
MULLANA (AMBALA)
Program: BCA
Course: BCA-402: Python Programming

In simpler terms, the data attribute is like a pointer to the memory location where the array's data is
stored in the computer's memory.
Let's see an example.

import numpy as np

array1 = [Link]([6, 7, 8])


array2 = [Link]([[1, 2, 3],
[6, 7, 8]])

# print memory address of array1's and array2's data


print("\nData of array1 is: ",[Link])
print("Data of array2 is: ",[Link])
Output

Data of array1 is: <memory at 0x7f746fea4a00>


Data of array2 is: <memory at 0x7f746ff6a5a0>

Here, the data attribute returns the memory addresses of the data
for array1 and array2 respectively.

[Link]

23 | P a g e

You might also like