0% found this document useful (0 votes)
3 views

numpy

The document provides an overview of NumPy, a library for numerical computing in Python, detailing how to create and manipulate arrays, including operations like reshaping, indexing, and applying mathematical functions. It covers basic array creation methods, array properties, and various operations such as addition, multiplication, and sorting. Additionally, it lists commonly used NumPy commands for array manipulation and analysis.

Uploaded by

pardhapradeep824
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

numpy

The document provides an overview of NumPy, a library for numerical computing in Python, detailing how to create and manipulate arrays, including operations like reshaping, indexing, and applying mathematical functions. It covers basic array creation methods, array properties, and various operations such as addition, multiplication, and sorting. Additionally, it lists commonly used NumPy commands for array manipulation and analysis.

Uploaded by

pardhapradeep824
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

07/09/2024, 19:30 numpy

Arrays in NumPy

In [1]: import numpy as np

# Creating array object


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

# Printing type of arr object


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

# Printing array dimensions (axes)


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

# Printing shape of array


print("Shape of array: ", arr.shape # rows X column

# Printing size (total number of elements) of array


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

# Printing type of elements in array


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

Array is of type: <class 'numpy.ndarray'>


No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int32

In [3]: # Creating array from list with type float


a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)

# Creating array from tuple


b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)

Array created using passed list:


[[1. 2. 4.]
[5. 8. 7.]]

Array created using passed tuple:


[1 3 2]

In [5]: # Creating a 3X4 array with all zeros


c = np.zeros((3, 4))
print ("An array initialized with all zeros:\n", c)

# Create a constant value array of complex type


d = np.full((3, 3), 6, dtype = 'complex')
print ("An array initialized with all 6s."
"Array type is complex:\n", d)

# Create an array with random values


e = np.random.random((2, 2))
print ("A random array:\n", e)

localhost:8888/lab/tree/numpy.ipynb 1/7
07/09/2024, 19:30 numpy

An array initialized with all zeros:


[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
An array initialized 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.02936169 0.08791751]
[0.42909047 0.46881495]]

In [7]: # Create a sequence of integers


# from 0 to 30 with steps of 5
f = np.arange(0, 30, 5)
print ("A sequential array with steps of 5:\n", f)

A sequential array with steps of 5:


[ 0 5 10 15 20 25]

In [13]: # Create a sequence of 10 values in range 0 to 5


g = np.linspace(0, 5, 10)
print ("A sequential array with 10 values between 0 and 5:\n", g)

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

In [17]: # Reshaping 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:\n", arr)


print("---------------")
print ("Reshaped array:\n", newarr)

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

In [19]: # Flatten array


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

print ("Original array:\n", arr)


print ("Fattened array:\n", flat_arr)

localhost:8888/lab/tree/numpy.ipynb 2/7
07/09/2024, 19:30 numpy

Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]

NumPy Array Indexing

Slicing: Just like lists in Python, NumPy arrays can be sliced. As arrays can be
multidimensional, you need to specify a slice for each dimension of the array. Integer
array indexing: In this method, lists are passed for indexing for each dimension. One-to-
one mapping of corresponding elements is done to construct a new arbitrary array.
Boolean array indexing: This method is used when we want to pick element s from the
array which satisfy some condition.

In [21]: # Python program to demonstrate


# indexing in numpy
import numpy as np

# An exemplar array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])

# Slicing array
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate"
"columns(0 and 2):\n", temp)

# Integer array indexing example


temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]
print ("\nElements at indices (0, 3), (1, 2), (2, 1),"
"(3, 0):\n", temp)

# boolean array indexing example


cond = arr > 0 # cond is a boolean array
temp = arr[cond]
print ("\nElements greater than 0:\n", temp)

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

NumPy Basic Operations

1. Operations on a single NumPy array

In [ ]: # Python program to demonstrate


# basic operations on single array
import numpy as np

localhost:8888/lab/tree/numpy.ipynb 3/7
07/09/2024, 19:30 numpy

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

# add 1 to every 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 each element


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

# modify existing array


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

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

print ("\nOriginal array:\n", a)


print ("Transpose of array:\n", a.T)

NumPy – Unary Operators

In [23]: # Python program to demonstrate


# unary operators in numpy
import numpy as np

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


[4, 7, 2],
[3, 1, 9]])

# maximum element of array


print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:",
arr.max(axis = 1))

# minimum element of array


print ("Column-wise minimum elements:",
arr.min(axis = 0))

# sum of array elements


print ("Sum of all array elements:",
arr.sum())

# cumulative sum along each row


print ("Cumulative sum along each row:\n",
arr.cumsum(axis = 1))

localhost:8888/lab/tree/numpy.ipynb 4/7
07/09/2024, 19:30 numpy

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

NumPy – Binary Operators

In [25]: # Python program to demonstrate


# binary operators in Numpy
import numpy as np

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

# add arrays
print ("Array sum:\n", a + b)

# multiply arrays (elementwise multiplication)


print ("Array multiplication:\n", a*b)

# matrix multiplication
print ("Matrix multiplication:\n", a.dot(b))

Array sum:
[[5 5]
[5 5]]
Array multiplication:
[[4 6]
[6 4]]
Matrix multiplication:
[[ 8 5]
[20 13]]

NymPy’s ufuncs NumPy provides familiar mathematical functions such as sin, cos, exp,
etc.

In [27]: # Python program to demonstrate


# universal functions in numpy
import numpy as np

# create an array of sine values


a = np.array([0, np.pi/2, np.pi])
print ("Sine values of array elements:", np.sin(a))

# exponential values
a = np.array([0, 1, 2, 3])
print ("Exponent of array elements:", np.exp(a))

# square root of array values


print ("Square root of array elements:", np.sqrt(a))

localhost:8888/lab/tree/numpy.ipynb 5/7
07/09/2024, 19:30 numpy

Sine values of array elements: [0.0000000e+00 1.0000000e+00 1.2246468e-16]


Exponent of array elements: [ 1. 2.71828183 7.3890561 20.08553692]
Square root of array elements: [0. 1. 1.41421356 1.73205081]

NumPy Sorting Arrays

In [29]: # Python program to demonstrate sorting in numpy


import numpy as np

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

# sorted array
print ("Array elements in sorted order:\n",
np.sort(a, axis = None))

# sort array row-wise


print ("Row-wise sorted array:\n",
np.sort(a, axis = 1))

# specify sort algorithm


print ("Column wise sort by applying merge-sort:\n",
np.sort(a, axis = 0, kind = 'mergesort'))

# Example to show sorting of structured array


# set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]

# Values to be put in array


values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]

# Creating array
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",
np.sort(arr, order = 'name'))

print ("Array sorted by graduation year and then cgpa:\n",


np.sort(arr, order = ['grad_year', 'cgpa']))

Array elements in sorted order:


[-1 0 1 2 3 4 4 5 6]
Row-wise sorted array:
[[ 1 2 4]
[ 3 4 6]
[-1 0 5]]
Column wise sort by applying merge-sort:
[[ 0 -1 2]
[ 1 4 5]
[ 3 4 6]]

Array sorted by names:


[(b'Aakash', 2009, 9. ) (b'Ajay', 2008, 8.7) (b'Hrithik', 2009, 8.5)
(b'Pankaj', 2008, 7.9)]
Array sorted by graduation year and then cgpa:
[(b'Pankaj', 2008, 7.9) (b'Ajay', 2008, 8.7) (b'Hrithik', 2009, 8.5)
(b'Aakash', 2009, 9. )]

localhost:8888/lab/tree/numpy.ipynb 6/7
07/09/2024, 19:30 numpy

What are NumPy Commands? NumPy commands refer to the functions and methods
available in the NumPy library that operate on arrays. Here are a few commonly used
NumPy commands:

np.array(): Create an array.


np.arange(): Return evenly spaced values within a given
interval.
np.zeros(), np.ones(), np.full(): Create new arrays filled with
zeros,
ones, or a specified value,
respectively.
np.dot(): Dot product of two arrays.
np.reshape(): Gives a new shape to an array without changing its
data.
np.mean(), np.median(), np.std(): Compute the mean, median, and
standard deviation of array elements.
np.linalg.inv(): Compute the (multiplicative) inverse of a
matrix.

localhost:8888/lab/tree/numpy.ipynb 7/7

You might also like