Docsity

NumPy: A Comprehensive Guide to Python's Array Library, Study notes of Computer Science

Partial preview of the text

Download NumPy: A Comprehensive Guide to Python's Array Library and more Study notes Computer Science in PDF only on Docsity!

Numpy

Manpreet Kaur(Python and Data Science

Manpreet Kaur(Python and Data Science

Numpy library is written in c language.

There are three major advantages :

  • Fast Process
  • Use less memory to store data
  • Convenient

Manpreet Kaur(Python and Data Science

Manpreet Kaur(Python and Data Science

(numpy)

Manpreet Kaur(Python and Data Science

First run below commands in cmd window.

  • pip list
  • pip install numpy (https://pypi.org/project/numpy/)

How to install Numpy

Import NumPy

Manpreet Kaur(Python and Data Science

Data Types in NumPy

NumPy has some extra data types, and refer to data types with one character, like i for integers, u for unsigned

integers etc.

Below is a list of all data types in NumPy and the characters used to represent them.

  • i - integer
  • b - boolean
  • u - unsigned integer
  • f - float
  • c - complex float
  • m - timedelta
  • M - datetime
  • O - object
  • S - string
  • U - unicode string
  • V - fixed chunk of memory for other type ( void )

Manpreet Kaur(Python and Data Science

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 :

import numpy as np

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

print(arr.dtype)

Manpreet Kaur(Python and Data Science

array() Function

Manpreet Kaur(Python and Data Science

Creating 1D Arrya using array() Function

Manpreet Kaur(Python and Data Science

index

Manpreet Kaur(Python and Data Science

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.

Example :

Import numpy as np

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

Print(arr1)

Print(type(arr1)

Ourtput :

[1 2 3 4 5]

<class ‘numpy.ndarray’>

Create a NumPy ndarray Object

Manpreet Kaur(Python and Data Science

Check Number of Dimensions?

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

Example :

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)

Manpreet Kaur(Python and Data Science

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 :

import numpy as np

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

print(arr) print('number of dimensions :', arr.ndim)

Manpreet Kaur(Python and Data Science