{"id":18029,"date":"2017-07-28T16:15:32","date_gmt":"2017-07-28T13:15:32","guid":{"rendered":"http:\/\/www.webcodegeeks.com\/?p=18029"},"modified":"2018-01-09T09:30:18","modified_gmt":"2018-01-09T07:30:18","slug":"python-numpy-array-tutorial","status":"publish","type":"post","link":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/","title":{"rendered":"Python NumPy Array Tutorial"},"content":{"rendered":"<p>Today we will be talking about one useful library that is used in data science. Now, why do we need a library and can&#8217;t use Python itself? Well, we can actually use Python itself, but once you get familiar with working in <code>NumPy<\/code>, you will see the difference.<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n[ulp id=&#8217;R7QVpFMZmjosABLC&#8217;]<\/p>\n<div class=\"toc\">\n<h3>Table Of Contents<\/h3>\n<dl>\n<dt><a href=\"#whatisnumpy\">1. What is NumPy? <\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#installing\">1.1. Installing NumPy<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#workingwitharrays\">2. Working with Arrays<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#array\">2.1. Arrays manipulation<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dd>\n<dl>\n<dt><a href=\"#numpy\">2.2. NumPy arrays<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dd>\n<dl>\n<dt><a href=\"#index\">2.3. Indexing<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dd>\n<dl>\n<dt><a href=\"#data\">2.4. Datatypes<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dd>\n<dl>\n<dt><a href=\"#math\">2.5. NumPy Math<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#broadcast\">3. Broadcasting<\/a><\/dt>\n<dt><a href=\"#summary\">4. Summary<\/a><\/dt>\n<dt><a href=\"#homework\">5.Homework<\/a><\/dt>\n<dt><a href=\"#download\">6.Download the Source Code<\/a><\/dt>\n<\/dl>\n<\/div>\n<h2><a name=\"whatisnumpy\"><\/a>1. What is NumPy?<\/h2>\n<p>NumPy is the core library and foundation for data science. It works great with multidimensional array objects. The library&#8217;s name is short for <i>&#8220;Numerical Python&#8221;<\/i>. So basically what we do with it is solve on a computer mathematical models of problems in Science and Engineering. It&#8217;s far more efficient just to use this library instead of writing your own in Python, because it&#8217;s already got all features you need. So let&#8217;s get started, shall we?<\/p>\n<h3><a name=\"installing\"><\/a>1.1 Installing NumPy<\/h3>\n<p>You need to install NumPy before working with it. It&#8217;s not a pre-installed library in your computer. By now, you need to have at least Python installed in your computer. We will do the most common way of installing which is <code>pip<\/code>.<br \/>\nIf you are Windows user, try this:<\/p>\n<p><span style=\"text-decoration: underline\"><em>Windows installation<\/em><\/span><\/p>\n<pre class=\"brush:bash\">pip3 install numpy\r\n<\/pre>\n<p>Note that it may now work, so there are 2 solutions: either add Python to the PATH environment, or check if you have <code>pip<\/code> installed. If you don&#8217;t, then try this:<\/p>\n<p><span style=\"text-decoration: underline\"><em>Windows installation<\/em><\/span><\/p>\n<pre class=\"brush:bash\">pip install pip --upgrade\r\npip --version\r\n<\/pre>\n<p>Then you need to download wheel from the Internet and install it. Then you will be ready to go. Now, if you are a Linux user, this one will help: Go to command line by this<code>Ctrl<\/code>+<code>Alt<\/code>+<code>T<\/code> or any other combination you have in your distribution. Then type:<\/p>\n<p><span style=\"text-decoration: underline\"><em>Linux installation<\/em><\/span><\/p>\n<pre class=\"brush:bash\">sudo pip3 install numpy\r\n<\/pre>\n<p>That&#8217;s it! Now you are ready to code!<\/p>\n<h2><a name=\"workingwitharrays\"><\/a>2. Working with arrays<\/h2>\n<h3><a name=\"array\"><\/a>2.1. Arrays manipulation<\/h3>\n<p>We already know what an array is. It&#8217;s a grid of values of the same type. An array represents any regular data in a structured way. For example, you may have an array of strings, integers, booleans, etc. Let&#8217;s create one:<\/p>\n<p><span style=\"text-decoration: underline\"><em>Python Shell<\/em><\/span><\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; my_array = [1,2,3]\r\n&gt;&gt;&gt; print(my_array)\r\n[1, 2, 3]\r\n&gt;&gt;&gt; my_2d_array = [4,[5,6],7]\r\n&gt;&gt;&gt; print(my_2d_array)\r\n[4, [5, 6], 7]\r\n&gt;&gt;&gt; my_3d_array = [8,[9,[10,11],12],13]\r\n&gt;&gt;&gt; print(my_3d_array)\r\n[8, [9, [10, 11], 12], 13]\r\n<\/pre>\n<p>As we can see, we have got couple arrays representing integers. However, if we dive into Computer Science, an array actually contains more than just elements. It contains information about the raw data, where and how to locate elements in the array and how to interpret them. Let&#8217;s talk about 4 basic aspects of manipulating arrays:<\/p>\n<ul>\n<li><code>data<\/code> is a pointer that shows the memory address of the first byte in the array. It&#8217;s important to know it before you do any manipulations with it<\/li>\n<li><code>dtype<\/code> is a data type pointer that shows what kind of elements are displayed in the given array<\/li>\n<li><code>shape<\/code> indicates the shape of the given array. It can be multidimensional, so it&#8217;s wise to know about the shape<\/li>\n<li><code>strides<\/code> is something really tricky. It shows how many bytes are needed to be skipped in order to hop on a different element in the given array. It&#8217;s a pretty confusing explanation. Imagine that you just can&#8217;t get access to another element and you just don&#8217;t see it, unless you pay an effort to skip some bytes. It&#8217;s more of a pointer logic, but it&#8217;s really important to understand it well<\/li>\n<\/ul>\n<h3><a name=\"numpy\"><\/a>2.2. NumPy arrays<\/h3>\n<p>In order to create a numpy array we need to use the <code>np.array()<\/code> function. It&#8217;s a common practice to import numpy as <code>np<\/code>. That&#8217;s what we will do as well in this article. Let&#8217;s create couple arrays:<\/p>\n<p><span style=\"text-decoration: underline\"><em>array.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\na = np.array([1,2,3,4,5])\r\nprint(type(a))\r\n#outputs &lt;class 'numpy.ndarray'&gt;\r\n\r\nprint(a.shape)\r\n#outputs (3,)\r\n\r\nprint(a.dtype)\r\n#outputs int64\r\n\r\nprint(a.strides)\r\n#outputs (8,)\r\n\r\nprint(a.data)\r\n#check the output for yourself!\r\n<\/pre>\n<p>So it&#8217;s all pretty simple when it comes to accessing elements and initializing arrays. But what happens if we want to create arrays?<\/p>\n<p><span style=\"text-decoration: underline\"><em>numpy_array.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\n#create an array of all zeros\r\na = np.zeros((3,3))\r\nprint(a)\r\n'''\r\n[[ 0.  0.  0.]\r\n [ 0.  0.  0.]\r\n [ 0.  0.  0.]]\r\n'''\r\n\r\n#create an array of all ones\r\nb = np.ones((2,3))\r\nprint(b)\r\n'''\r\n[[ 1.  1.  1.]\r\n [ 1.  1.  1.]]\r\n'''\r\n\r\n#create a constant array with a custom shape and custom value\r\nc = np.full((4,3),2)\r\nprint(c)\r\n'''\r\n[[2 2 2]\r\n [2 2 2]\r\n [2 2 2]\r\n [2 2 2]]\r\n'''\r\n\r\n#create an identity matrix with a custom shape\r\nd = np.eye(4)\r\nprint(d)\r\n'''\r\n[[ 1.  0.  0.  0.]\r\n [ 0.  1.  0.  0.]\r\n [ 0.  0.  1.  0.]\r\n [ 0.  0.  0.  1.]]\r\n'''\r\n\r\n#create random array\r\ne = np.random.random((3,3))\r\n#it might print something similar to somewhat below:\r\n'''\r\n[[ 0.59678947  0.89766843  0.04795142]\r\n [ 0.1575911   0.54953419  0.21916215]\r\n [ 0.69233153  0.99744842  0.89032515]]\r\n'''\r\n<\/pre>\n<h3><a name=\"index\"><\/a>2.3. Indexing<\/h3>\n<p>We can manipulate arrays in many ways. One of them is called slicing. Let&#8217;s try to modify an array with modifying sliced sub-array only.<\/p>\n<p><span style=\"text-decoration: underline\"><em>indexing.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\n#create an array\r\na = np.array([[1,2,3,4,5], [6,7,8,9,10],[11,12,13,14,15]])\r\nprint(a)\r\n'''\r\n[[ 1  2  3  4  5]\r\n [ 6  7  8  9 10]\r\n [11 12 13 14 15]]\r\n'''\r\n\r\n#Now let's obtain sub-array consisting of 3x3 array in the middle of the given array\r\nb = a[:3, 1:4]\r\nprint(b)\r\n'''\r\n[[ 2  3  4]\r\n [ 7  8  9]\r\n [12 13 14]]\r\n'''\r\n\r\n#as we modify b array, we actually modify the given a array. Let's make all elements there equal zeros\r\nfor i in range(3):\r\n   for j in range(3):\r\n      b[i,j] = 0\r\nprint(b)\r\n'''\r\n[[0 0 0]\r\n [0 0 0]\r\n [0 0 0]]\r\n'''\r\n\r\n#now let's see how our first array changed:\r\nprint(a)\r\n'''\r\n[[ 1  0  0  0  5]\r\n [ 6  0  0  0 10]\r\n [11  0  0  0 15]]\r\n'''\r\n<\/pre>\n<p>Now you may be wondering why did the given array change? If so, it&#8217;s a good question! Since a slice of an array is a view into the same data, so modifying it will change the original array. Makes sense, right?<br \/>\nSo there is another thing which can be quite confusing. You may extract the very similar data but Python will say it&#8217;s different. Let me show you the code first, and then I will explain what is happening there:<\/p>\n<p><span style=\"text-decoration: underline\"><em>row_col.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\n#create a 3x3 array\r\na = np.array([[1,2,3], [4,5,6], [7,8,9]])\r\n'''\r\n[[1 2 3]\r\n [4 5 6]\r\n [7 8 9]]\r\n'''\r\n\r\n#example with rows\r\nrow_r1 = a[1, :]\r\nrow_r2 = a[1:2, :]\r\n\r\nprint(row_r1, row_r1.shape)\r\n# [4 5 6] (3,)\r\nprint(row_r2, row_r2.shape)\r\n# [[4 5 6]] (1, 3)\r\n\r\n#example with columns\r\ncol_r1 = a[:, 1]\r\ncol_r2 = a[:, 1:2]\r\n\r\nprint(col_r1, col_r1.shape)\r\n#[2 5 8] (3,)\r\nprint(col_r2, col_r2.shape)\r\n'''\r\n[[2]\r\n [5]\r\n [8] (3, 1)\r\n'''\r\n<\/pre>\n<p>Alright, time for the explanation! We can mix integer indexing with slices yields an array of a lower rank, while using only slices yields an array of the same rank as the original array. We can do the same distinction when accessing columns.<br \/>\nAnyway, that&#8217;s quite a useful trick. Also, we can mutate elements in arrays.<\/p>\n<p><span style=\"text-decoration: underline\"><em>arrange.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\n#let's create 4x4 array\r\na = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]])\r\nprint(a)\r\n'''\r\n[[ 1  2  3  4]\r\n [ 5  6  7  8]\r\n [ 9 10 11 12]\r\n [13 14 15 16]]\r\n'''\r\n\r\n#let's create an array of indexes\r\nb = np.array([0,1,2,3])\r\nprint(b)\r\n#[0 1 2 3]\r\n\r\n#for each row we extract the element of b's elements indexes\r\n print(a[np.arrange(4), b])\r\n#[ 1  6 11 16]\r\n\r\n'''\r\nSo we basically iterate the first row and look for 0th element (b[0] = 0) and it's 1 (a[0][0] = 1). Then we do the same for the rest of rows: (a[1][1] = 6, a[2][2] = 11, a[3][3] = 16\r\n'''\r\n\r\n#let's mutate some elements of the array:\r\na[np.arrange(4), b] = 0\r\nprint(a)\r\n'''\r\n[[ 0  2  3  4]\r\n [ 5  0  7  8]\r\n [ 9 10  0 12]\r\n [13 14 15  0]]\r\n'''\r\n<\/pre>\n<p>Another cool feature is a boolean indexing. We can pick out arbitrary elements of an array. It is used to pick elements which satisfy some <code>if-else<\/code> statements.<\/p>\n<p><span style=\"text-decoration: underline\"><em>bool.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\na = np.array([[1,2,3], [4,5,6], [7,8,9]])\r\n\r\n#let's find all elements that are greater than 5\r\nbool_idx = (a&gt;5)\r\n\r\n#let's print them!\r\nprint(bool_idx)\r\n\r\n#what if we want to know indexes of those elements? No problem!\r\nprint(a[bool_idx])\r\n\r\n#we can actually do it altogether\r\nprint(a[a&gt;5])\r\n<\/pre>\n<h3><a name=\"data\"><\/a>2.4. Datatypes<\/h3>\n<p>Do you know why NumPy is great? It tries to guess a datatype when you create an array, but functions that construct arrays also include (usually) an optional argument to explicitly specify the datatype.<\/p>\n<p><span style=\"text-decoration: underline\"><em>datatype.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\na = np.array([1,2])\r\nprint(a.dtype)\r\n#int64\r\n\r\na = np.array([1.1, 2.2])\r\nprint(a.dtype)\r\n#float64\r\n\r\na = np.array([1,2], dtype = np.int64)\r\nprint(a.dtype)\r\n#int64\r\n<\/pre>\n<p>So note that we can actually clarify what kind of data we want to put in our variables. Here is a short list of what you can do:<\/p>\n<ul>\n<li style=\"list-style-type: none\">\n<ul>\n<li><code>\"?\"<\/code> is a boolean<\/li>\n<li><code>\"b\"<\/code> is a signed byte<\/li>\n<li><code>\"B\"<\/code> is an unsigned byte<\/li>\n<li><code>\"i\"<\/code> is a signed integer<\/li>\n<li><code>\"u\"<\/code> is an unsigned integer<\/li>\n<li><code>\"f\"<\/code> is a floating-point<\/li>\n<li><code>\"c\"<\/code> is a complex-floating point<\/li>\n<li><code>\"m\"<\/code> is a timedelta<\/li>\n<li><code>\"M\"<\/code> is a datetime<\/li>\n<li><code>\"O\"<\/code> is an object<\/li>\n<li><code>\"U\"<\/code> is a unicode string<\/li>\n<li><code>\"V\"<\/code> is a raw data known as <code>void<\/code><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h3><a name=\"math\"><\/a>2.5. NumPy Math<\/h3>\n<p>You can perform mathematical functions on arrays. Let&#8217;s see how they work!<\/p>\n<p><span style=\"text-decoration: underline\"><em>math.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\na = np.array([[1,2],[3,4]], dtype=np.float64)\r\nb = np.array([[5,6],[7,8]], dtype=np.float64)\r\n\r\nprint(a+b)\r\n'''\r\n[[  6.   8.]\r\n [ 10.  12.]]\r\n'''\r\nprint(np.add(a,b))\r\n'''\r\n[[  6.   8.]\r\n [ 10.  12.]]\r\n'''\r\n\r\nprint(a-b)\r\n'''\r\n[[-4. -4.]\r\n [-4. -4.]]\r\n'''\r\nprint(np.subtract(a,b))\r\n'''\r\n[[-4. -4.]\r\n [-4. -4.]]\r\n'''\r\n\r\nprint(a*b)\r\n'''\r\n[[  5.  12.]\r\n [ 21.  32.]]\r\n'''\r\nprint(np.multiply(a,b))\r\n'''\r\n[[  5.  12.]\r\n [ 21.  32.]]\r\n'''\r\n\r\nprint(a\/b)\r\n''' \r\n[[ 0.2         0.33333333]\r\n [ 0.42857143  0.5       ]]\r\n'''\r\nprint(np.divide(a,b))\r\n''' \r\n[[ 0.2         0.33333333]\r\n [ 0.42857143  0.5       ]]\r\n'''\r\n\r\nprint(a**b)\r\n'''\r\n[[  1.00000000e+00   6.40000000e+01]\r\n [  2.18700000e+03   6.55360000e+04]]\r\n'''\r\nprint(np.sqrt(a) + np.sqrt(b))\r\n'''\r\n[ 3.23606798  3.86370331]\r\n [ 4.37780212  4.82842712]]\r\n'''\r\n<\/pre>\n<p>We can also work in NumPy with vectors. It seems obvious since we have been working with matrices for the past 10 minutes. Anyway, we can use <code>dot<\/code> function to compute inner products of vectors, to multiply matrices and to multiply vector by a matrix. Let&#8217;s see how it works!<\/p>\n<p><span style=\"text-decoration: underline\"><em>product.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\na = np.array([[1,2], [3,4]])\r\nb = np.array([[5,6], [7,8]])\r\n\r\nx = np.array([9,10])\r\ny = np.array([11, 12])\r\n\r\n#Vector\/Vector product\r\nprint(v.dot(w))\r\n#219\r\nprint(np.dot(v,w))\r\n#219\r\n\r\n#Matrix\/Vector product\r\nprint(x.dot(v))\r\n#[29 67]\r\nprint(np.dot(x, v))\r\n#[29 67]\r\n\r\n#Matrix\/Matrix product\r\nprint(x.dot(y))\r\n#\r\nprint(np.dot(x,y))\r\n'''\r\n[[19 22]\r\n [43 50]]\r\n'''\r\n<\/pre>\n<p>Another commonly used thing is <code>sum<\/code>. Let&#8217;s see how it works!<\/p>\n<p><span style=\"text-decoration: underline\"><em>sum.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\n a = np.array([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]])\r\n\r\nprint(np.sum(a))\r\n#210\r\n\r\nprint(np.sum(a, axis = 0))\r\n#[34 38 42 46 50]\r\n#it's a sum of each column above!\r\n\r\nprint(np.sum(a, axis = 1))\r\n#[15 40 65 90]\r\n#it's a sum of each row above!\r\n<\/pre>\n<p>Apart from computing and manipulating matrices, we can also transpose matrices. We just need to use <code>T<\/code> method. Let&#8217;s see how it works!<\/p>\n<p><span style=\"text-decoration: underline\"><em>transpose.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\na = np.array([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]])\r\nprint(a)\r\n'''\r\n[[ 1  2  3  4  5]\r\n [ 6  7  8  9 10]\r\n [11 12 13 14 15]\r\n [16 17 18 19 20]]\r\n'''\r\nprint(a.T)\r\n'''\r\n[[ 1  6 11 16]\r\n [ 2  7 12 17]\r\n [ 3  8 13 18]\r\n [ 4  9 14 19]\r\n [ 5 10 15 20]]\r\n'''\r\n<\/pre>\n<h2><a name=\"broadcast\"><\/a>3. Broadcasting<\/h2>\n<p>Broadcasting is something powerful that allows you to work with arrays of different shapes when performing arithmetic operations. Suppose we have a matrix and want to add a constant static vector to each row of it. We can do something like this (even though there are many other ways to do it):<\/p>\n<p><span style=\"text-decoration: underline\"><em>broadcasting.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\r\nv = np.array([1, 0, 1])\r\n\r\n#create an empty matrix with the same size as x\r\ny = np.empty_like(x) \r\n\r\nfor i in range(4):\r\n   y[i, :] = x[i, :] + v\r\n\r\nprint(y)\r\n'''\r\n[[ 2 2 4]\r\n [ 5 5 7]\r\n [ 8 8 10]\r\n [ 11 11 13]]\r\n'''\r\n<\/pre>\n<p>Basically what we do here is stacking multiple copies of vector vertically and performing elementwise summation. We can do it other way like this:<\/p>\n<p><span style=\"text-decoration: underline\"><em>stack.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\r\nv = np.array([1, 0, 1])\r\nvv = np.tile(v, (4, 1)) \r\n\r\nprint(vv)\r\n'''\r\n[[ 1 0 1]\r\n [ 1 0 1]\r\n [ 1 0 1]\r\n [ 1 0 1]]\r\n'''\r\ny = x + vv\r\nprint(y)\r\n'''\r\n[[ 2 2 4]\r\n [ 5 5 7]\r\n [ 8 8 10]\r\n [ 11 11 13]]\r\n'''\r\n<\/pre>\n<p>So what does broadcasting have to do with all this? Well, it actually helps you to perform computation without creating multiple copies of <code>v<\/code>. What about this code?<\/p>\n<p><span style=\"text-decoration: underline\"><em>no_copies.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import numpy as np\r\n\r\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\r\nv = np.array([1, 0, 1])\r\n\r\ny = x + v\r\n'''\r\nThis line works even though x has shape(4,3) and v has shape (3,) due to broadcasting\r\n'''\r\n\r\nprint(y)\r\n'''\r\n[[ 2 2 4]\r\n [ 5 5 7]\r\n [ 8 8 10]\r\n [ 11 11 13]]\r\n'''\r\n<\/pre>\n<p>There are couple things to remember when it comes to broadcasting 2 arrays together:<\/p>\n<ul>\n<li>The arrays can be broadcast together if they are compatible in all dimensions<\/li>\n<li>After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays<\/li>\n<li>Arrays are compatible in a dimension if (and only if) they have the same size in the dimension, or if one of the arrays has size 1 in that dimension<\/li>\n<\/ul>\n<h2><a name=\"summary\"><\/a>4. Summary<\/h2>\n<p>For now, we have a basic understanding about NumPy and how to work with NumPy arrays. Let&#8217;s sum up what we have learned, and I will also provide links to official documentation:<\/p>\n<ul>\n<li>You can create arrays and manipulate them, mutate elements inside and do many cool things! More info about creating arrays can be found <a href=\"https:\/\/docs.scipy.org\/doc\/numpy\/user\/basics.creation.html#arrays-creation\">here<\/a> and more info about array manipulation is <a href=\"https:\/\/docs.scipy.org\/doc\/numpy\/reference\/routines.array-manipulation.html\"> there<\/a><\/li>\n<li>You can index objects in arrays in many different ways: basic slicing, field access, advanced indexing. More about indexing is up <a href=\"https:\/\/docs.scipy.org\/doc\/numpy\/user\/basics.creation.html#arrays-creation\">here<\/a><\/li>\n<li>You can perform all sorts of mathematical miracles in NumPy. Actually, if you are using it and want to become a data scientist, maybe there are no miracles but calculations for you! Anyway, more info about mathematical functions is up <a href=\"https:\/\/docs.scipy.org\/doc\/numpy\/user\/basics.creation.html#arrays-creation\">here<\/a><\/li>\n<li>You can do broadcasting which is very powerful and makes your code run faster. More info about that is <a href=\"https:\/\/docs.scipy.org\/doc\/numpy\/user\/basics.broadcasting.html\">here<\/a><\/li>\n<li>For any general references it&#8217;s always wise to go to official docs to solve your problems. Surely, I should put a link to official docs which is <a href=\"https:\/\/docs.scipy.org\/doc\/numpy\/\">here<\/a><\/li>\n<\/ul>\n<h2><a name=\"homework\"><\/a>5. Homework<\/h2>\n<p>It&#8217;s always good to practice what you have just learned. So I encourage you to solve these exercises.<\/p>\n<ol>\n<li>How to randomly place p elements in a 2D array?<\/li>\n<li>Find the nearest value from a given value in an array<\/li>\n<li>Considering a four dimensions array, how to get sum over the last two axis at once?<\/li>\n<li>How to swap two rows of an array?<\/li>\n<li>Compute a matrix rank<\/li>\n<\/ol>\n<\/ul>\n<h2><a name=\"download\"><\/a>6. Download the Source Code<\/h2>\n<p>You can find all materials needed in the file below.<\/p>\n<div class=\"download\"><strong>Downoload<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/python-numpy-array.zip\"><strong>python-numpy-array.zip<\/strong><\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Today we will be talking about one useful library that is used in data science. Now, why do we need a library and can&#8217;t use Python itself? Well, we can actually use Python itself, but once you get familiar with working in NumPy, you will see the difference. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &hellip;<\/p>\n","protected":false},"author":657,"featured_media":1651,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[53],"tags":[355,481,480,290],"class_list":["post-18029","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-array","tag-data-science","tag-numpy","tag-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Python NumPy Array Tutorial - Web Code Geeks - 2026<\/title>\n<meta name=\"description\" content=\"We will be talking about NumPy array and what role it plays in modern data science. We will study techniques to work efficiently and write fast code\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python NumPy Array Tutorial - Web Code Geeks - 2026\" \/>\n<meta property=\"og:description\" content=\"We will be talking about NumPy array and what role it plays in modern data science. We will study techniques to work efficiently and write fast code\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/\" \/>\n<meta property=\"og:site_name\" content=\"Web Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/webcodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2017-07-28T13:15:32+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2018-01-09T07:30:18+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Aleksandr Krasnov\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@webcodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@webcodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Aleksandr Krasnov\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/\"},\"author\":{\"name\":\"Aleksandr Krasnov\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/e07867bd46d3c03c70d9566277772373\"},\"headline\":\"Python NumPy Array Tutorial\",\"datePublished\":\"2017-07-28T13:15:32+00:00\",\"dateModified\":\"2018-01-09T07:30:18+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/\"},\"wordCount\":1509,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"keywords\":[\"array\",\"data science\",\"numpy\",\"python\"],\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/\",\"name\":\"Python NumPy Array Tutorial - Web Code Geeks - 2026\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"datePublished\":\"2017-07-28T13:15:32+00:00\",\"dateModified\":\"2018-01-09T07:30:18+00:00\",\"description\":\"We will be talking about NumPy array and what role it plays in modern data science. We will study techniques to work efficiently and write fast code\",\"breadcrumb\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#primaryimage\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.webcodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python\",\"item\":\"https:\/\/www.webcodegeeks.com\/category\/python\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Python NumPy Array Tutorial\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"name\":\"Web Code Geeks\",\"description\":\"Web Developers Resource Center\",\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.webcodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/webcodegeeks\",\"https:\/\/x.com\/webcodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/e07867bd46d3c03c70d9566277772373\",\"name\":\"Aleksandr Krasnov\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/773b350dfd4fa0aa4470113fe22f39c38db44fc456aef63c609bf8f05e424dc6?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/773b350dfd4fa0aa4470113fe22f39c38db44fc456aef63c609bf8f05e424dc6?s=96&d=mm&r=g\",\"caption\":\"Aleksandr Krasnov\"},\"description\":\"Aleksandr is passionate about teaching programming. His main interests are Neural Networks, Python and Web development. Hobbies are game development and translating. For the past year, he has been involved in different international projects as SEO and IT architect.\",\"url\":\"https:\/\/www.webcodegeeks.com\/author\/aleksandr-krasnov\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python NumPy Array Tutorial - Web Code Geeks - 2026","description":"We will be talking about NumPy array and what role it plays in modern data science. We will study techniques to work efficiently and write fast code","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/","og_locale":"en_US","og_type":"article","og_title":"Python NumPy Array Tutorial - Web Code Geeks - 2026","og_description":"We will be talking about NumPy array and what role it plays in modern data science. We will study techniques to work efficiently and write fast code","og_url":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/","og_site_name":"Web Code Geeks","article_publisher":"https:\/\/www.facebook.com\/webcodegeeks","article_published_time":"2017-07-28T13:15:32+00:00","article_modified_time":"2018-01-09T07:30:18+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","type":"image\/jpeg"}],"author":"Aleksandr Krasnov","twitter_card":"summary_large_image","twitter_creator":"@webcodegeeks","twitter_site":"@webcodegeeks","twitter_misc":{"Written by":"Aleksandr Krasnov","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#article","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/"},"author":{"name":"Aleksandr Krasnov","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/e07867bd46d3c03c70d9566277772373"},"headline":"Python NumPy Array Tutorial","datePublished":"2017-07-28T13:15:32+00:00","dateModified":"2018-01-09T07:30:18+00:00","mainEntityOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/"},"wordCount":1509,"commentCount":0,"publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","keywords":["array","data science","numpy","python"],"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/","url":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/","name":"Python NumPy Array Tutorial - Web Code Geeks - 2026","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#primaryimage"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","datePublished":"2017-07-28T13:15:32+00:00","dateModified":"2018-01-09T07:30:18+00:00","description":"We will be talking about NumPy array and what role it plays in modern data science. We will study techniques to work efficiently and write fast code","breadcrumb":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#primaryimage","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.webcodegeeks.com\/python\/python-numpy-array-tutorial\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.webcodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Python","item":"https:\/\/www.webcodegeeks.com\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Python NumPy Array Tutorial"}]},{"@type":"WebSite","@id":"https:\/\/www.webcodegeeks.com\/#website","url":"https:\/\/www.webcodegeeks.com\/","name":"Web Code Geeks","description":"Web Developers Resource Center","publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.webcodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.webcodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.webcodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/webcodegeeks","https:\/\/x.com\/webcodegeeks"]},{"@type":"Person","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/e07867bd46d3c03c70d9566277772373","name":"Aleksandr Krasnov","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/773b350dfd4fa0aa4470113fe22f39c38db44fc456aef63c609bf8f05e424dc6?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/773b350dfd4fa0aa4470113fe22f39c38db44fc456aef63c609bf8f05e424dc6?s=96&d=mm&r=g","caption":"Aleksandr Krasnov"},"description":"Aleksandr is passionate about teaching programming. His main interests are Neural Networks, Python and Web development. Hobbies are game development and translating. For the past year, he has been involved in different international projects as SEO and IT architect.","url":"https:\/\/www.webcodegeeks.com\/author\/aleksandr-krasnov\/"}]}},"_links":{"self":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/18029","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/users\/657"}],"replies":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/comments?post=18029"}],"version-history":[{"count":0,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/18029\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media\/1651"}],"wp:attachment":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media?parent=18029"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/categories?post=18029"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/tags?post=18029"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}