You are on page 1of 21

{

"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Day_5_Numpy_Part_1.ipynb",
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "yNMy_TNjUrdd"
},
"source": [
"## **Introduction to NumPy:**\n",
"```NumPy``` stands for *Numerical Python* and it's a fundamental package
for scientific computing in Python. NumPy provides Python with an extensive math
library capable of performing numerical computations effectively and efficiently.
These lessons are intended as a basic overview of NumPy and introduces some of its
most important features.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "oPnpCMIeYA90"
},
"source": [
"## **Why Numpy:**\n",
"You may be wondering why people use NumPy - after all, Python can handle
lists, as you learned in the Intro to Python lessons.\n",
"\n",
"Even though Python lists are great on their own, NumPy has a number of key
features that give it great advantages over Python lists. One such feature is
speed. When performing operations on large arrays NumPy can often perform several
orders of magnitude faster than Python lists. This speed comes from the nature of
NumPy arrays being memory-efficient and from optimized algorithms used by NumPy for
doing arithmetic, statistical, and linear algebra operations."
]
},
{
"cell_type": "code",
"metadata": {
"id": "1D9wUejeTCUi"
},
"source": [
"import time\n",
"import numpy as np"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "cx33B30cYJzv"
},
"source": [
"x = np.random.rand(1000000000)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "xXpuBxHLYOWg",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 54
},
"outputId": "e72cc273-38e1-4398-8aa1-6f08f9a776f3"
},
"source": [
"start = time.time()\n",
"mean = sum(x)/len(x)\n",
"print(time.time() - start)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"164.07553839683533\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "zwi39jQRYkye",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 54
},
"outputId": "11d53351-1df7-4e2c-e5cb-71c9ffd2185d"
},
"source": [
"start = time.time()\n",
"mean_np = np.mean(x)\n",
"print(time.time() - start)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"0.6675674915313721\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Dibh7I4LcMdb"
},
"source": [
"## **Creating NumPy ndarrays:**\n",
"At the core of NumPy is the ndarray, where nd stands for n-dimensional. An
ndarray is a multidimensional array of elements all of the same type. In other
words, an ndarray is a grid that can take on many shapes and can hold either
numbers or strings. In many Machine Learning problems you will often find yourself
using ndarrays in many different ways. For instance, you might use an ndarray to
hold the pixel values of an image that will be fed into a Neural Network for image
classification."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6XWJHaq0cabp"
},
"source": [
"There are several ways to create ndarrays in NumPy. In the following
lessons we will see two ways to create ndarrays:\n",
"\n",
"1. Using regular Python lists\n",
"\n",
"2. Using built-in NumPy functions"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "itKv0T1acqnf"
},
"source": [
"In this section, we will create ndarrays by providing Python lists to the
NumPy np.array() function, it is just a function that returns an ndarray. We should
note that for the purposes of clarity, the examples throughout these lessons will
use small and simple ndarrays. Let's start by creating 1-Dimensional (1D)
ndarrays."
]
},
{
"cell_type": "code",
"metadata": {
"id": "bUHEilP2ZN5J",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 54
},
"outputId": "13235ae1-b467-40b6-9c17-18f8082e2ef8"
},
"source": [
"# We import NumPy into Python\n",
"import numpy as np\n",
"\n",
"# We create a 1D ndarray that contains only integers\n",
"x = np.array([1, 2, 3, 4, 5])\n",
"\n",
"# Let's print the ndarray we just created using the print() command\n",
"print('x = ', x)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"x = [1 2 3 4 5]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Oi4x0r2fvwSd"
},
"source": [
"## **Shape of an ndarray:**\n",
"Another important property of arrays is their shape. The shape of an array
is the size along each of its dimensions. As you will see, NumPy ndarrays have
attributes that allows us to get information about them in a very intuitive way.
For example, the shape of an ndarray can be obtained using the .shape attribute.
The shape attribute returns a tuple of N positive integers that specify the sizes
of each dimension."
]
},
{
"cell_type": "code",
"metadata": {
"id": "xskCTsNRc2HK",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 137
},
"outputId": "fc340f5a-ff85-47f0-bb26-306106ad797e"
},
"source": [
"# We create a 1D ndarray that contains only integers\n",
"x = np.array([1, 2, 3, 4, 5])\n",
"\n",
"# We print x\n",
"print()\n",
"print('x = ', x)\n",
"print()\n",
"\n",
"# We print information about x\n",
"print('x has dimensions:', x.shape)\n",
"print('x is an object of type:', type(x))\n",
"print('The elements in x are of type:', x.dtype)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"x = [1 2 3 4 5]\n",
"\n",
"x has dimensions: (5,)\n",
"x is an object of type: <class 'numpy.ndarray'>\n",
"The elements in x are of type: int64\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MLYrG8oLwXb2"
},
"source": [
"We can see that the shape attribute returns the tuple (5,) telling us that
x is of rank 1 (i.e. x only has 1 dimension ) and it has 5 elements. The type()
function tells us that x is indeed a NumPy ndarray. Finally, the .dtype attribute
tells us that the elements of x are stored in memory as signed 64-bit integers.
Another great advantage of NumPy is that it can handle more data-types than Python
lists.[here](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DTCnuASsz3mq"
},
"source": [
"As mentioned earlier, ndarrays can also hold strings. Let's see how we can
create a rank 1 ndarray of strings in the same manner as before, by providing the
np.array() function a Python list of strings."
]
},
{
"cell_type": "code",
"metadata": {
"id": "W3rhKGfAwAOH",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 137
},
"outputId": "c7b085a7-ac97-4e3d-aa93-8757291e7ef4"
},
"source": [
"# We create a rank 1 ndarray that only contains strings\n",
"x = np.array(['Hello', 'World'])\n",
"\n",
"# We print x\n",
"print()\n",
"print('x = ', x)\n",
"print()\n",
"\n",
"# We print information about x\n",
"print('x has dimensions:', x.shape)\n",
"print('x is an object of type:', type(x))\n",
"print('The elements in x are of type:', x.dtype)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"x = ['Hello' 'World']\n",
"\n",
"x has dimensions: (2,)\n",
"x is an object of type: <class 'numpy.ndarray'>\n",
"The elements in x are of type: <U5\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XaJ8fHUx0Ey7"
},
"source": [
"It is important to remember that one big difference between Python lists
and ndarrays, is that unlike Python lists, all the elements of an ndarray must be
of the same type. So, while we can create Python lists with both integers and
strings, we can't mix types in ndarrays. If you provide the np.array() function
with a Python list that has both integers and strings, NumPy will interpret all
elements as strings. We can see this in the next example:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "ACE0Mqcrz5-E",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 137
},
"outputId": "f20b73e7-fd02-47f1-d9ed-20923c0da42d"
},
"source": [
"# We create a rank 1 ndarray from a Python list that contains integers and
strings\n",
"x = np.array([1, 2, 'World'])\n",
"\n",
"# We print the ndarray\n",
"print()\n",
"print('x = ', x)\n",
"print()\n",
"\n",
"# We print information about x\n",
"print('x has dimensions:', x.shape)\n",
"print('x is an object of type:', type(x))\n",
"print('The elements in x are of type:', x.dtype)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"x = ['1' '2' 'World']\n",
"\n",
"x has dimensions: (3,)\n",
"x is an object of type: <class 'numpy.ndarray'>\n",
"The elements in x are of type: <U21\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PFK0xNh-1hkE"
},
"source": [
"Let us now look at how we can create a rank 2 ndarray from a nested Python
list."
]
},
{
"cell_type": "code",
"metadata": {
"id": "mCEls7XS0IDI",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 220
},
"outputId": "600e0e6e-35cc-4bea-e8c5-85cfc3fca72a"
},
"source": [
"# We create a rank 2 ndarray that only contains integers\n",
"Y = np.array([[1,2,3],[4,5,6],[7,8,9], [10,11,12]])\n",
"\n",
"# We print Y\n",
"print()\n",
"print('Y = \\n', Y)\n",
"print()\n",
"\n",
"# We print information about Y\n",
"print('Y has dimensions:', Y.shape)\n",
"print('Y has a total of', Y.size, 'elements')\n",
"print('Y is an object of type:', type(Y))\n",
"print('The elements in Y are of type:', Y.dtype)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Y = \n",
" [[ 1 2 3]\n",
" [ 4 5 6]\n",
" [ 7 8 9]\n",
" [10 11 12]]\n",
"\n",
"Y has dimensions: (4, 3)\n",
"Y has a total of 12 elements\n",
"Y is an object of type: <class 'numpy.ndarray'>\n",
"The elements in Y are of type: int64\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BEGW5NcV1uK5"
},
"source": [
"Up to now, we have only created ndarrays with integers and strings. We saw
that when we create an ndarray with only integers, NumPy will automatically assign
the dtype int64 to its elements. Let's see what happens when we create ndarrays
with floats and integers."
]
},
{
"cell_type": "code",
"metadata": {
"id": "bb26oQPg1jty",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 87
},
"outputId": "9a62d4b3-72e7-4ace-c6c0-e9c518b0e34f"
},
"source": [
"# We create a rank 1 ndarray that contains integers\n",
"x = np.array([1,2,3])\n",
"\n",
"# We create a rank 1 ndarray that contains floats\n",
"y = np.array([1.0,2.0,3.0])\n",
"\n",
"# We create a rank 1 ndarray that contains integers and floats\n",
"z = np.array([1, 2.5, 4])\n",
"\n",
"# We print the dtype of each ndarray\n",
"print('The elements in x are of type:', x.dtype)\n",
"print('The elements in y are of type:', y.dtype)\n",
"print('The elements in z are of type:', z.dtype)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"The elements in x are of type: int64\n",
"The elements in y are of type: float64\n",
"The elements in z are of type: float64\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0z7cLmFD17Kw"
},
"source": [
"Notice that when we create an ndarray with both floats and integers, as we
did with the z ndarray above, NumPy assigns its elements a *float64* dtype as well.
This is called upcasting. Since all the elements of an ndarray must be of the same
type, in this case NumPy upcasts the integers in z to floats in order to avoid
losing precision in numerical computations."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XUmzWrvr2AVp"
},
"source": [
"Even though NumPy automatically selects the dtype of the ndarray, NumPy
also allows you to specify the particular dtype you want to assign to the elements
of the ndarray. You can specify the dtype when you create the ndarray using the
keyword dtype in the np.array() function. Let's see an example:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "_BSEAZgQ1wsx",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 104
},
"outputId": "da136eb8-2dd9-4c3b-f048-1fa9b9e5a740"
},
"source": [
"# We create a rank 1 ndarray of floats but set the dtype to int64\n",
"x = np.array([1.5, 2.2, 3.7, 4.0, 5.9], dtype = np.int64)\n",
"\n",
"# We print x\n",
"print()\n",
"print('x = ', x)\n",
"print()\n",
"\n",
"# We print the dtype x\n",
"print('The elements in x are of type:', x.dtype)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"x = [1 2 3 4 5]\n",
"\n",
"The elements in x are of type: int64\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "IIo6BbvW23A3"
},
"source": [
"Once you create an ndarray, you may want to save it to a file to be read
later or to be used by another program. NumPy provides a way to save the arrays
into files for later use - let's see how this is done."
]
},
{
"cell_type": "code",
"metadata": {
"id": "heCxnnFC2UcA"
},
"source": [
"# We create a rank 1 ndarray\n",
"x = np.array([1, 2, 3, 4, 5])\n",
"\n",
"# We save x into the current directory as \n",
"np.save('my_array', x)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "2zclAmaE28Ki"
},
"source": [
"The above saves the x ndarray into a file named my_array.npy. You can load
the saved ndarray into a variable by using the load() function."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fqT_YREU3Bug"
},
"source": [
"> When loading an array from a file, make sure you include the name of the
file together with the extension .npy, otherwise you will get an error."
]
},
{
"cell_type": "code",
"metadata": {
"id": "A0LqlywX26AG",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "8971e9de-9229-4e21-aab8-53b548734066"
},
"source": [
"# We load the saved array from our current directory into variable y\n",
"y = np.load('my_array.npy')\n",
"\n",
"# We print y\n",
"print()\n",
"print('y = ', y)\n",
"print()\n",
"\n",
"# We print information about the ndarray we loaded\n",
"print('y is an object of type:', type(y))\n",
"print('The elements in y are of type:', y.dtype)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"y = [1 2 3 4 5]\n",
"\n",
"y is an object of type: <class 'numpy.ndarray'>\n",
"The elements in y are of type: int64\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xHA3hotizZoq"
},
"source": [
"## **np.reshape():**\n",
"We can use these functions to create rank 2 ndarrays of any shape by
combining them with the np.reshape() function. The np.reshape(ndarray, new_shape)
function converts the given ndarray into the specified new_shape. It is important
to note that the new_shape should be compatible with the number of elements in the
given ndarray."
]
},
{
"cell_type": "code",
"metadata": {
"id": "CBGX8P2Bzaf_",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 253
},
"outputId": "da911b43-4adb-40e9-bc4d-7ab97a5863ea"
},
"source": [
"# We create a rank 1 ndarray with sequential integers from 0 to 19\n",
"x = np.arange(20)\n",
"\n",
"# We print x\n",
"print()\n",
"print('Original x = ', x)\n",
"print()\n",
"\n",
"# We reshape x into a 4 x 5 ndarray \n",
"x = np.reshape(x, (4,5))\n",
"\n",
"# We print the reshaped x\n",
"print()\n",
"print('Reshaped x = \\n', x)\n",
"print()\n",
"\n",
"# We print information about the reshaped x\n",
"print('x has dimensions:', x.shape)\n",
"print('x is an object of type:', type(x))\n",
"print('The elements in x are of type:', x.dtype) "
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original x = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 19]\n",
"\n",
"\n",
"Reshaped x = \n",
" [[ 0 1 2 3 4]\n",
" [ 5 6 7 8 9]\n",
" [10 11 12 13 14]\n",
" [15 16 17 18 19]]\n",
"\n",
"x has dimensions: (4, 5)\n",
"x is an object of type: <class 'numpy.ndarray'>\n",
"The elements in x are of type: int64\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "EZHoy2duz-v6"
},
"source": [
"One great feature about NumPy, is that some functions can also be applied
as methods. This allows us to apply different functions in sequence in just one
line of code. ndarray methods are similar to ndarray attributes in that they are
both applied using dot notation (.). Let's see how we can accomplish the same
result as in the above example, but in just one line of code:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "vm5wTd5oze11",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 203
},
"outputId": "8f12e4a7-53e8-48bf-9e62-93b0487aba85"
},
"source": [
"# We create a a rank 1 ndarray with sequential integers from 0 to 19 and\
n",
"# reshape it to a 4 x 5 array \n",
"Y = np.arange(20).reshape(4, 5)\n",
"\n",
"# We print Y\n",
"print()\n",
"print('Y = \\n', Y)\n",
"print()\n",
"\n",
"# We print information about Y\n",
"print('Y has dimensions:', Y.shape)\n",
"print('Y is an object of type:', type(Y))\n",
"print('The elements in Y are of type:', Y.dtype)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Y = \n",
" [[ 0 1 2 3 4]\n",
" [ 5 6 7 8 9]\n",
" [10 11 12 13 14]\n",
" [15 16 17 18 19]]\n",
"\n",
"Y has dimensions: (4, 5)\n",
"Y is an object of type: <class 'numpy.ndarray'>\n",
"The elements in Y are of type: int64\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wIbAPL5A7V1N"
},
"source": [
"## **Accessing Elements in ndarays:**\n",
"Elements can be accessed using indices inside square brackets, [ ]. NumPy
allows you to use both positive and negative indices to access elements in the
ndarray. Positive indices are used to access elements from the beginning of the
array, while negative indices are used to access elements from the end of the
array. "
]
},
{
"cell_type": "code",
"metadata": {
"id": "ZfjHHvWs7vYO"
},
"source": [
"# We create a rank 1 ndarray that contains integers from 1 to 5\n",
"x = np.array([1, 2, 3, 4, 5])\n",
"\n",
"# We print x\n",
"print()\n",
"print('x = ', x)\n",
"print()\n",
"\n",
"# Let's access some elements with positive indices\n",
"print('This is First Element in x:', x[0]) \n",
"print('This is Second Element in x:', x[1])\n",
"print('This is Fifth (Last) Element in x:', x[4])\n",
"print()\n",
"\n",
"# Let's access the same elements with negative indices\n",
"print('This is First Element in x:', x[-5])\n",
"print('This is Second Element in x:', x[-4])\n",
"print('This is Fifth (Last) Element in x:', x[-1])"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "bbYr59qc8arb"
},
"source": [
"## Modifying ndarrays:\n",
"Now let's see how we can change the elements in rank 1 ndarrays. We do
this by accessing the element we want to change and then using the = sign to assign
the new value:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "yQwCZwSD85Q5",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 137
},
"outputId": "c7855e58-b67e-46cc-b966-f39ca0180d0a"
},
"source": [
"# We create a rank 1 ndarray that contains integers from 1 to 5\n",
"x = np.array([1, 2, 3, 4, 5])\n",
"\n",
"# We print the original x\n",
"print()\n",
"print('Original:\\n x = ', x)\n",
"print()\n",
"\n",
"# We change the fourth element in x from 4 to 20\n",
"x[3] = 20\n",
"\n",
"# We print x after it was modified \n",
"print('Modified:\\n x = ', x)\n"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original:\n",
" x = [1 2 3 4 5]\n",
"\n",
"Modified:\n",
" x = [ 1 2 3 20 5]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "W-G-2CNy8-Kn"
},
"source": [
"Similarly, we can also access and modify specific elements of rank 2
ndarrays. To access elements in rank 2 ndarrays we need to provide 2 indices in the
form [row, column]. Let's see some examples"
]
},
{
"cell_type": "code",
"metadata": {
"id": "fHV8Q1Ik863v",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 186
},
"outputId": "e580a229-0b25-40ff-f7a8-20749eb84ea3"
},
"source": [
"# We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9\n",
"X = np.array([[1,2,3],[4,5,6],[7,8,9]])\n",
"\n",
"# We print X\n",
"print()\n",
"print('X = \\n', X)\n",
"print()\n",
"\n",
"# Let's access some elements in X\n",
"print('This is (0,0) Element in X:', X[0,0])\n",
"print('This is (0,1) Element in X:', X[0,1])\n",
"print('This is (2,2) Element in X:', X[2,2])"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"X = \n",
" [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n",
"\n",
"This is (0,0) Element in X: 1\n",
"This is (0,1) Element in X: 2\n",
"This is (2,2) Element in X: 9\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kgQ4DUxZ9FPK"
},
"source": [
"Elements in rank 2 ndarrays can be modified in the same way as with rank 1
ndarrays. Let's see an example:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "uMP5cJ-P9A1P",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 236
},
"outputId": "b0faf293-8a41-49b6-fe30-6f498201538e"
},
"source": [
"# We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9\n",
"X = np.array([[1,2,3],[4,5,6],[7,8,9]])\n",
"\n",
"# We print the original x\n",
"print()\n",
"print('Original:\\n X = \\n', X)\n",
"print()\n",
"\n",
"# We change the (0,0) element in X from 1 to 20\n",
"X[0,0] = 20\n",
"\n",
"# We print X after it was modified \n",
"print('Modified:\\n X = \\n', X)\n"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original:\n",
" X = \n",
" [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n",
"\n",
"Modified:\n",
" X = \n",
" [[20 2 3]\n",
" [ 4 5 6]\n",
" [ 7 8 9]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ZWSEPc159LEG"
},
"source": [
"## **Adding and Deleting elements:**\n",
"Now, let's take a look at how we can add and delete elements from
ndarrays. We can delete elements using the np.delete(ndarray, elements, axis)
function. This function deletes the given list of elements from the given ndarray
along the specified axis. For rank 1 ndarrays the axis keyword is not required. For
rank 2 ndarrays, axis = 0 is used to select rows, and axis = 1 is used to select
columns. Let's see some examples:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "DRB_V6dd9HlM",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 335
},
"outputId": "b266340c-159d-42ee-d627-a109d0ccb75b"
},
"source": [
"# We create a rank 1 ndarray \n",
"x = np.array([1, 2, 3, 4, 5])\n",
"\n",
"# We create a rank 2 ndarray\n",
"Y = np.array([[1,2,3],[4,5,6],[7,8,9]])\n",
"\n",
"# We print x\n",
"print()\n",
"print('Original x = ', x)\n",
"\n",
"# We delete the first and last element of x\n",
"x = np.delete(x, [0,4])\n",
"\n",
"# We print x with the first and last element deleted\n",
"print()\n",
"print('Modified x = ', x)\n",
"\n",
"# We print Y\n",
"print()\n",
"print('Original Y = \\n', Y)\n",
"\n",
"# We delete the first row of y\n",
"w = np.delete(Y, 0, axis=0)\n",
"\n",
"# We delete the first and last column of y\n",
"v = np.delete(Y, [0,2], axis=1)\n",
"\n",
"# We print w\n",
"print()\n",
"print('w = \\n', w)\n",
"\n",
"# We print v\n",
"print()\n",
"print('v = \\n', v)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original x = [1 2 3 4 5]\n",
"\n",
"Modified x = [2 3 4]\n",
"\n",
"Original Y = \n",
" [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n",
"\n",
"w = \n",
" [[4 5 6]\n",
" [7 8 9]]\n",
"\n",
"v = \n",
" [[2]\n",
" [5]\n",
" [8]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Nqqwxir99XFI"
},
"source": [
"We can append values to ndarrays using the np.append(ndarray, elements,
axis) function. This function appends the given list of elements to ndarray along
the specified axis. Let's see some examples:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "Jv73CPgz9UYw",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 352
},
"outputId": "06adb68e-fe58-42eb-ee4e-56c8b2958ca8"
},
"source": [
"# We create a rank 1 ndarray \n",
"x = np.array([1, 2, 3, 4, 5])\n",
"\n",
"# We create a rank 2 ndarray \n",
"Y = np.array([[1,2,3],[4,5,6]])\n",
"\n",
"# We print x\n",
"print()\n",
"print('Original x = ', x)\n",
"\n",
"# We append the integer 6 to x\n",
"x = np.append(x, 6)\n",
"\n",
"# We print x\n",
"print()\n",
"print('x = ', x)\n",
"\n",
"# We append the integer 7 and 8 to x\n",
"x = np.append(x, [7,8])\n",
"\n",
"# We print x\n",
"print()\n",
"print('x = ', x)\n",
"\n",
"# We print Y\n",
"print()\n",
"print('Original Y = \\n', Y)\n",
"\n",
"# We append a new row containing 7,8,9 to y\n",
"v = np.append(Y, [[7,8,9]], axis=0)\n",
"\n",
"# We append a new column containing 9 and 10 to y\n",
"q = np.append(Y,[[9],[10]], axis=1)\n",
"\n",
"# We print v\n",
"print()\n",
"print('v = \\n', v)\n",
"\n",
"# We print q\n",
"print()\n",
"print('q = \\n', q)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original x = [1 2 3 4 5]\n",
"\n",
"x = [1 2 3 4 5 6]\n",
"\n",
"x = [1 2 3 4 5 6 7 8]\n",
"\n",
"Original Y = \n",
" [[1 2 3]\n",
" [4 5 6]]\n",
"\n",
"v = \n",
" [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n",
"\n",
"q = \n",
" [[ 1 2 3 9]\n",
" [ 4 5 6 10]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WsIxKWUN9gRr"
},
"source": [
"Now let's see now how we can insert values to ndarrays. We can insert
values to ndarrays using the np.insert(ndarray, index, elements, axis) function.
This function inserts the given list of elements to ndarray right before the given
index along the specified axis. Let's see some examples:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "7oFcymIm9bTR"
},
"source": [
"# We create a rank 1 ndarray \n",
"x = np.array([1, 2, 5, 6, 7])\n",
"\n",
"# We create a rank 2 ndarray \n",
"Y = np.array([[1,2,3],[7,8,9]])\n",
"\n",
"# We print x\n",
"print()\n",
"print('Original x = ', x)\n",
"\n",
"# We insert the integer 3 and 4 between 2 and 5 in x. \n",
"x = np.insert(x,2,[3,4])\n",
"\n",
"# We print x with the inserted elements\n",
"print()\n",
"print('x = ', x)\n",
"\n",
"# We print Y\n",
"print()\n",
"print('Original Y = \\n', Y)\n",
"\n",
"# We insert a row between the first and last row of y\n",
"w = np.insert(Y,1,[4,5,6],axis=0)\n",
"\n",
"# We insert a column full of 5s between the first and second column of y\
n",
"v = np.insert(Y,1,5, axis=1)\n",
"\n",
"# We print w\n",
"print()\n",
"print('w = \\n', w)\n",
"\n",
"# We print v\n",
"print()\n",
"print('v = \\n', v)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "NoFIMQQu9ptw"
},
"source": [
""
],
"execution_count": null,
"outputs": []
}
]
}

You might also like