Open In App

Python Numpy

Last Updated : 13 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python.

Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data.

Arrays in Numpy

Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array.A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists.

Creating a Numpy Array
Arrays in Numpy can be created by multiple ways, with various number of Ranks, defining the size of the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc. The type of the resultant array is deduced from the type of the elements in the sequences.
Note: Type of array can be explicitly defined while creating the array.

Python
# Python program for
# Creation of Arrays
import numpy as np
 
# Creating a rank 1 Array
arr = np.array([1, 2, 3])
print("Array with Rank 1: \n",arr)
 
# Creating a rank 2 Array
arr = np.array([[1, 2, 3],
                [4, 5, 6]])
print("Array with Rank 2: \n", arr)
 
# Creating an array from tuple
arr = np.array((1, 3, 2))
print("\nArray created using "
      "passed tuple:\n", arr)

Output
Array with Rank 1: 
 [1 2 3]
Array with Rank 2: 
 [[1 2 3]
 [4 5 6]]

Array created using passed tuple:
 [1 3 2]

Accessing the array Index
In a numpy array, indexing or accessing the array index can be done in multiple ways. To print a range of an array, slicing is done. Slicing of an array is defining a range in a new array which is used to print a range of elements from the original array. Since, sliced array holds a range of elements of the original array, modifying content with the help of sliced array modifies the original array content.

Python
# Python program to demonstrate
# indexing in numpy array
import numpy as np
 
# Initial Array
arr = np.array([[-1, 2, 0, 4],
                [4, -0.5, 6, 0],
                [2.6, 0, 7, 8],
                [3, -7, 4, 2.0]])
print("Initial Array: ")
print(arr)
 
# Printing a range of Array
# with the use of slicing method
sliced_arr = arr[:2, ::2]
print ("Array with first 2 rows and"
    " alternate columns(0 and 2):\n", sliced_arr)
 
# Printing elements at
# specific Indices
Index_arr = arr[[1, 1, 0, 3], 
                [3, 2, 1, 0]]
print ("\nElements at indices (1, 3), "
    "(1, 2), (0, 1), (3, 0):\n", Index_arr)

Output
Initial Array: 
[[-1.   2.   0.   4. ]
 [ 4.  -0.5  6.   0. ]
 [ 2.6  0.   7.   8. ]
 [ 3.  -7.   4.   2. ]]
Array with first 2 rows and alternate columns(0 and 2):
 [[-1.  0.]
 [ 4.  6.]]

Elements a...

Basic Array Operations
In numpy, arrays allow a wide range of operations which can be performed on a particular array or a combination of Arrays. These operation include some basic Mathematical operation as well as Unary and Binary operations.

Python
# Python program to demonstrate
# basic operations on single array
import numpy as np
 
# Defining Array 1
a = np.array([[1, 2],
              [3, 4]])
 
# Defining Array 2
b = np.array([[4, 3],
              [2, 1]])
               
# Adding 1 to every element
print ("Adding 1 to every element:", a + 1)
 
# Subtracting 2 from each element
print ("\nSubtracting 2 from each element:", b - 2)
 
# sum of array elements
# Performing Unary operations
print ("\nSum of all array "
       "elements: ", a.sum())
 
# Adding two arrays
# Performing Binary operations
print ("\nArray sum:\n", a + b)

Output
Adding 1 to every element: [[2 3]
 [4 5]]

Subtracting 2 from each element: [[ 2  1]
 [ 0 -1]]

Sum of all array elements:  10

Array sum:
 [[5 5]
 [5 5]]

More on Numpy Arrays

Data Types in Numpy

Every Numpy array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. Every ndarray has an associated data type (dtype) object. This data type object (dtype) provides information about the layout of the array. The values of an ndarray are stored in a buffer which can be thought of as a contiguous block of memory bytes which can be interpreted by the dtype object. Numpy provides a large set of numeric datatypes that can be used to construct arrays. At the time of Array creation, Numpy tries to guess a datatype, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype.

Constructing a Datatype Object
In Numpy, datatypes of Arrays need not to be defined unless a specific datatype is required. Numpy tries to guess the datatype for Arrays which are not predefined in the constructor function.

Python
# Python Program to create
# a data type object
import numpy as np
 
# Integer datatype
# guessed by Numpy
x = np.array([1, 2])  
print("Integer Datatype: ")
print(x.dtype)         
 
# Float datatype
# guessed by Numpy
x = np.array([1.0, 2.0]) 
print("\nFloat Datatype: ")
print(x.dtype)  
 
# Forced Datatype
x = np.array([1, 2], dtype = np.int64)   
print("\nForcing a Datatype: ")
print(x.dtype)

Output
Integer Datatype: 
int64

Float Datatype: 
float64

Forcing a Datatype: 
int64

Math Operations on DataType array
In Numpy arrays, basic mathematical operations are performed element-wise on the array. These operations are applied both as operator overloads and as functions. Many useful functions are provided in Numpy for performing computations on Arrays such as sum: for addition of Array elements, T: for Transpose of elements, etc.

Python
# Python Program to create
# a data type object
import numpy as np
 
# First Array
arr1 = np.array([[4, 7], [2, 6]], 
                 dtype = np.float64)
                  
# Second Array
arr2 = np.array([[3, 6], [2, 8]], 
                 dtype = np.float64) 
 
# Addition of two Arrays
Sum = np.add(arr1, arr2)
print("Addition of Two Arrays: ")
print(Sum)
 
# Addition of all Array elements
# using predefined sum method
Sum1 = np.sum(arr1)
print("\nAddition of Array elements: ")
print(Sum1)
 
# Square root of Array
Sqrt = np.sqrt(arr1)
print("\nSquare root of Array1 elements: ")
print(Sqrt)
 
# Transpose of Array
# using In-built function 'T'
Trans_arr = arr1.T
print("\nTranspose of Array: ")
print(Trans_arr)

Output
Addition of Two Arrays: 
[[ 7. 13.]
 [ 4. 14.]]

Addition of Array elements: 
19.0

Square root of Array1 elements: 
[[2.         2.64575131]
 [1.41421356 2.44948974]]

Transpose of Array: 
[[4. 2.]
 ...

More on Numpy Data Type

Methods in Numpy:

all()diag()hypot()ones_like()
any()diagflat()absolute()full_like()
take()diag_indices()ceil()sin()
put()asmatrix()floor()cos()
apply_along_axis()bmat()degrees()tan()
apply_over_axes()eye()radians()sinh()
argmin()roll()npv()cosh()
argmax()identity()fv()tanh()
nanargmin()arange()pv()arcsin()
nanargmax()place()power()arccos()
amax()extract()float_power()exp()
amin()compress()log()exp2()
insert()rot90()log1()fix()
delete()tile()log2()logical_or()
append()reshape()log10()logical_and()
around()ravel()dot()logical_not()
flip()isinf()vdot()logical_xor()
fliplr()isrealobj()trunc()array_equal()
flipud()isscalar()divide()array_equiv()
triu()isneginf()floor_divide()arctan2()
tril()isposinf()true_divide()equal()
tri()iscomplex()random.rand()not_equal()
empty()isnan()random.randn()less()
empty_like()iscomplexobj()ndarray.flat()less_equal()
zeros()isreal()expm1()greater()
zeros_like()isfinite()bincount()greater_equal()
ones()isfortran()rint()prod()
arctan()cbrt()square()

Programs on Numpy

Useful Numpy Articles



Previous Article
Next Article

Similar Reads

Python | Numpy numpy.resize()
With the help of Numpy numpy.resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing. Parameters: new_shape : [tuple of ints, or n ints] Shape of resized array refcheck : [bool, optio
2 min read
Python | Numpy numpy.transpose()
With the help of Numpy numpy.transpose(), We can perform the simple function of transpose within one line by using numpy.transpose() method of Numpy. It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays. This method transpose the 2-D numpy array. Parameters: axes : [None, tuple of ints, or n ints] If anyone wants to pass
2 min read
Python | Numpy numpy.ndarray.__lt__()
With the help of numpy.ndarray.__lt__() method of Numpy, We can find that which element in an array is less than the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__lt__($self, value, /) Return: self<value Example #1 : In this example we can see that
1 min read
Python | Numpy numpy.ndarray.__gt__()
With the help of numpy.ndarray.__gt__() method of Numpy, We can find that which element in an array is greater then the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__gt__($self, value, /) Return: self>value Example #1 : In this example we can see th
1 min read
Python | Numpy numpy.ndarray.__le__()
With the help of numpy.ndarray.__le__() method of Numpy, We can find that which element in an array is less than or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__le__($self, value, /) Return: self<=value Example #1 : In this example we
1 min read
Python | Numpy numpy.ndarray.__ge__()
With the help of numpy.ndarray.__ge__() method of Numpy, We can find that which element in an array is greater then or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__ge__($self, value, /) Return: self>=value Example #1 : In this example
1 min read
Python | Numpy numpy.ndarray.__ne__()
With the help of numpy.ndarray.__ne__() method of Numpy, We can find that which element in an array is not equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__ne__($self, value, /) Return: self!=value Example #1 : In this example we can see that
1 min read
Python | Numpy numpy.ndarray.__neg__()
With the help of numpy.ndarray.__neg__() method of Numpy, one can multiply each and every element of an array with -1. Hence, the resultant array having values like positive values becomes negative and negative values become positive. Syntax: ndarray.__neg__($self, /) Return: -self Example #1 : In this example we can see that after applying numpy._
1 min read
Python | Numpy numpy.ndarray.__pos__()
With the help of numpy.ndarray.__pos__() method of Numpy, one can multiply each and every element of an array with 1. Hence, the resultant array having values same as original array. Syntax: ndarray.__pos__($self, /) Return: +self Example #1 : In this example we can see that after applying numpy.__pos__(), we get the simple array that can be the sa
1 min read
Python | Numpy numpy.ndarray.__truediv__()
With the help of Numpy numpy.ndarray.__truediv__(), we can divide a particular value that is provided as a parameter in the ndarray.__truediv__() method. Value will be divided to each and every element in a numpy array. Syntax: ndarray.__truediv__($self, value, /) Return: self/value Example #1 : In this example, we can see that each element in an a
1 min read
Article Tags :