NumPy in Python | Kit 1 (Introduction)

Arrays | NumPy | Python Methods and Functions

What is NumPy?
NumPy — it is a versatile package for handling arrays. It provides a high-performance multidimensional array object and tools for working with these arrays.

This is a fundamental package for scientific computing with Python. It contains various functions, including the following important ones:

  • Powerful N-dimensional array of objects
  • Complex (broadcast) functions
  • Code integration tools C / C ++ and Fortran
  • Useful Linear Algebra, Fourier Transform, and Random Number Capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multidimensional shared data container ...
Arbitrary data types can be defined using Numpy, allowing NumPy to easily and quickly integrate with a wide variety of databases.

Setting :

  • Mac users and Linux can install NumPy using the pip command:
     pip install numpy 
  • B Windows there is no package manager like Linux or Mac.
    Please download the preinstalled Windows installer for NumPy from here (in depending on your system configuration and Python version).
    And then install the packages manually.

Note. All of the examples below will not work in the interactive IDE.

1. Arrays in NumPy: The main object of NumPy is a homogeneous multidimensional array.

  • This is a table of elements (usually numbers) of the same type, indexed by a set of natural numbers.
  • In NumPy the dimensions are called axes . Number of axles — rank .
  • The NumPy array class is named ndarray . This is also known as a array of aliases.

Example:

 [[1, 2, 3], [ 4, 2, 5]] Here, rank = 2 (as it is 2-dimensional or it has 2 axes) first dimension (axis) length = 2, second dimension has length = 3 overall shape can be expressed as: (2, 3) 

# Python program for demonstration
# basic array characteristics

import numpy as np

 
# Create an object array

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

  [ 4 , 2 , 5 ]])

  
# Print type of arr object

print ( "Array is of type:" , type ( arr))

 
# Print array dimensions (axes)

print ( "No. of dimensions: " , arr.ndim)

  
# Print array form

print ( "Shape of array:" , arr.shape)

 
# Print size (total number of elements) of array

print ( "Size of array:" , arr.size)

 
# Print type of items in the array

print ( " Array stores elements of type: " , arr.dtype)

Output:

 Array is of type: No. of dimension s: 2 Shape of array: (2, 3) Size of array: 6 Array stores elements of type: int64 

2. Creating Arrays. There are various ways to create arrays in NumPy.

  • For example, you can create an array from a regular list Python or tuple using the array function. The type of the resulting array is determined by the type of elements in the sequences.
  • Often array elements are initially unknown, but its size is known. Hence, NumPy offers several functions for creating arrays with initial placeholder contents. This minimizes the need to grow arrays, an expensive operation.
    For example: np.zeros, np.ones, np.full, np.empty, etc.
  • For creating sequences of numbers, NumPy provides a function similar to the range which returns arrays instead of lists.
  • arange: returns evenly spaced values ​​over a given range. stride is specified.
  • linspace: returns evenly spaced values ​​over a given interval. number no items are returned.
  • Rebuilding the array: We can use the RESHAPE method to change the array. Consider an array with the shape (a1, a2, a3,…, aN). We can change it and convert it to another array with the shape (b1, b2, b3,…, bM). The only prerequisite is:
    a1 x a2 x a3… x aN = b1 x b2 x b3… x bM. (i.e. the original size of the array remains unchanged.)
  • Flatten the array: we can use the flattening method to get a copy of the array collapsed into one dimension . It takes an order argument. The default is "C" (for the main row of rows). Use & # 39; F & # 39; for basic column order.

Note: the type of an array can be explicitly specified when the array is created.

# Python program for demonstration
# array creation methods

import numpy as np

 
# Create an array from a list with the float type

a = np.array ([[ 1 , 2 , 4 ], [ 5 , 8 , 7 ]], dtype = `float` )

print ( "Array created using passed list: " , a)

  
# Create an array from a tuple

b = np.array (( 1 , 3 , 2 ))

print ( "Array created using passed tuple:" , b)

 
# Create a 3X4 array with all zeros

c = np.zeros (( 3 , 4 ))

print ( "An array initialized with all zeros:" , c)

  
# Create an array of constant complex values ​​

d = np.full (( 3 , 3 ), 6 , dtype = `complex` )

print ( " An array initialized with al l 6s. " 

  " Array type is complex: " , d)

 
# Create an array with random values

e = np.random.random (( 2 , 2 ))

print ( "A random array:" , e)

 
# Create a sequence of integers
# from 0 to 30 in steps of 5

f = np.arange ( 0 , 30 , 5 )

print ( "A sequential array with steps of 5: " , f)

  
# Create a sequence of 10 values ​​ranging from 0 to 5

g = np.linspace ( 0 , 5 , 10 )

print ( "A sequential array with 10 values ​​between"

"0 and 5:" , g)

  
# Convert 3X4 array to 2X2X3 array

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

[ 5 , 2 , 4 , 2 ],

[ 1 , 2 , 0 , 1 ]])

 

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

 

print ( "Original array:" , arr)

print ( "Reshaped array:" , newarr)

 
# Flatten the array

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

flarr = arr.flatten ()

 

print ( "Original array:" , arr)

print ( "Fattened array:" , flarr)

Exit:

 Array created using passed list: [[1. 2. 4.] [5. 8. 7.]] Array created using passed tuple: [1 3 2] An array initialized with all zeros: [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] An array ini tialized with all 6s. Array type is complex: [[6. + 0.j 6. + 0.j 6. + 0.j] [6. + 0.j 6. + 0.j 6. + 0.j] [6. + 0.j 6. + 0.j 6. + 0.j]] A random array: [[0.46829566 0.67079389] [0.09079849 0.95410464]] A sequential array with steps of 5: [0 5 10 15 20 25] A sequential array with 10 values ​​between 0 and 5: [0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778 3.33333333 3.88888889 4.44444444 5.] Original array: [[1 2 3 4] [5 2 4 2] [1 2 0 1]] Reshaped array: [[ [1 2 3] [4 5 2]] [[4 2 1] [2 0 1]]] Original array: [[1 2 3] [4 5 6]] Fattened array: [1 2 3 4 5 6] 

3. Array Indexing. Knowing the basics of array indexing is important for parsing and manipulating an array object. NumPy offers many ways to index arrays.

  • Slicing: Like lists in Python, NumPy arrays can be sliced. Since arrays can be multidimensional, you need to specify a slice for each dimension of the array.
  • Indexing Integer Arrays: In this method, lists are passed for indexing for each dimension. One-to-one matching of matching elements is done to create a new arbitrary array.
  • Boolean Array Indexing: This method is used when we want to select elements from an array that satisfy some condition.

# Python program for demonstration
# numpy indexing

import numpy as np

 
# Sample array

arr = np.array ([[ - 1 , 2 , 0 , 4 ],

  [ 4 , - 0.5 , 6 , 0 ],

[ 2.6 , 0 , 7 , 8 ],

[ 3 , - 7 , 4 , 2.0 ]])

 
# Slicing an array

temp = arr [: 2 , :: 2 ]

print ( " Array with first 2 rows and alternate "

  " columns (0 and 2 ): " , temp)

  
# An example of indexing an integer array

temp = arr [[ 0 , 1 , 2 , 3 ], [ 3 , 2 , 1 , 0 ]]

print ( "Elements at indices (0, 3), (1, 2 ), (2, 1), "

  " (3, 0): " , temp)

 
# example of boolean array indexing

cond = arr & gt; 0 # cond is a boolean array

temp = arr [cond]

print ( " Elements greater than 0: " , temp)

Output:

 Array with first 2 rows and alternatecolumns (0 and 2): [[-1. 0.] [4. 6.]] Elements at indices (0, 3), (1, 2), (2, 1), (3, 0): [4. 6. 0. 3.] Elements greater than 0: [2. 4. 4. 6. 2.6 7. 8. 3. 4. 2.] 

4. Basic Operations: NumPy provides many built-in arithmetic functions.

  • Single Array Operations: we can use overloaded arithmetic operators to perform elementwise array operations to create a new array. In the case of operators + =, — =, * = the existing array is being modified.

# Python program for demonstration
# basic operations on one array

import numpy as np

 

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

  
# add 1 to each element

print ( "Adding 1 to every element:" , a + 1 )

 
# subtract 3 from each element

print ( "Subtracting 3 from each element:" , a - 3 )

 
# multiply each element by 10

print ( "Multiplying each element by 10:" , a * 10 )

 
# square of each element

print ( "Squaring each element:" , a * * 2 )

 
# modify existing array

a * = 2

print ( "Doubled each element of original array:" , a)

 
# transpose the array

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

  

print ( "Original array:" , a)

print ( " Transpose of array: " , aT)

Output:

 Adding 1 to every element: [2 3 6 4] Subtracting 3 from each element: [-2 -1 2 0] Multiplying each element by 10: [ 10 20 50 30] Squaring each element: [1 4 25 9] Doubled each element of original array: [2 4 10 6] Original array: [[1 2 3] [3 4 5] [9 6 0]] Transpose of array: [[1 3 9] [2 4 6] [3 5 0]] 
  • Unary Operators: Many unary operators are provided as a method of the ndarray class. This includes sum, minimum, maximum, and so on. These functions can also be applied row by row or by column by setting an axis parameter.

# Python program for demonstration
# unary operators in numpy

import numpy as np

 

arr = np.array ([[ 1 , 5 , 6 ],

[ 4 , 7 , 2 ],

[ 3 , 1 , 9 ]])

 
# maximum array element

print ( "Largest element is:" , arr. max ())

print ( " Row-wise maximum elements: " ,

  arr. max (axis = 1 ))

 
# minimum array element

print ( "Column-wise minimum elements:" ,

arr. min (axis = 0 ))

 
# sum of array elements

print ( "Sum of all array elements:" ,

arr. sum ())

 
# accumulated i sum for each row

print ( "Cumulative sum along each row:" ,

arr.cumsum (axis = 1 ))

Output:

 Largest element is: 9 Row-wise maximum elements: [6 7 9] Column-wise minimum elements: [1 1 2] Sum of all array elements: 38 Cumulative sum along each row: [[1 6 12] [4 11 13] [3 4 13 ]] 
  • Binary operators: these operations are applied to an array element by element, and a new array is created. You can use all the basic arithmetic operators like +, -, /, , etc. In the case of , the + =, — =, = the existing array is being modified.

# Python program for demonstration
# binary operators in Numpy

import numpy as np

 

a = np.array ([[ 1 , 2 ],

cellpadding = "0" cellspacing = "0">

# Python program for demonstration
# binary operators in Numpy

import numpy as np

 

a = np.array ([[ 1 , 2 ],

cellpadding = "0" cellspacing = "0">

# Python program for demonstration
# binary operators in Nu



Get Solution for free from DataCamp guru