{"id":1070,"date":"2019-12-17T03:55:41","date_gmt":"2019-12-17T03:55:41","guid":{"rendered":"https:\/\/www.askpython.com\/?p=1070"},"modified":"2020-05-22T16:48:52","modified_gmt":"2020-05-22T16:48:52","slug":"python-numpy-arrays","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/numpy\/python-numpy-arrays","title":{"rendered":"Python &#8211; An Introduction to NumPy Arrays"},"content":{"rendered":"\n<p>NumPy is the most commonly used scientific computing Python library. It provides a fast Pythonic interface, while still using the much faster C++ under the hood for computation. This ensures that the high-level readability and Pythonic features are still present while making the actual computation much faster than what pure Python code could. <\/p>\n\n\n\n<p>Here, we look at the data structure behind which NumPy does all of its work and how we could transform it in different ways similar to how we would manipulate other array-like data structures.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The NumPy Array object<\/h2>\n\n\n\n<p>To declare a numpy array object, we first import the <code>numpy<\/code> library, following which we instantiate our newly created array using the <code>np.array()<\/code> library function.<\/p>\n\n\n\n<p>The below snippet declares a simple 1-Dimensional numpy array:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; import numpy as np\n&gt;&gt;&gt; a = np.array(&#x5B;1, 2, 3, 4])\n&gt;&gt;&gt; print(a)\n&#x5B;1 2 3 4]\n<\/pre><\/div>\n\n\n<p>Each array has the following attributes :<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>ndim<\/code> (the number of dimensions)<\/li><li><code>shape<\/code> (the size of each dimension)<\/li><li><code>size<\/code> (the total size of the array)<\/li><li><code>dtype<\/code> (the datatype of the array)<\/li><\/ul>\n\n\n\n<p>NumPy array elements have the same data type, unlike <a href=\"https:\/\/www.askpython.com\/python\/list\/python-list\">Python lists<\/a>. We cannot make a single numpy array hold multiple different data types as a result.<\/p>\n\n\n\n<p>To declare a higher dimensional array, it is similar to declaring a higher dimensional array in any other language, using the appropriate matrix that represents the entire array.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Declare a 2-Dimensional numpy array\nb = np.array(&#x5B;&#x5B;1, 2, 3], &#x5B;4, 5, 6]])\nprint(&quot;b -&gt; ndim:&quot;, b.ndim)\nprint(&quot;b -&gt; shape:&quot;, b.shape)\nprint(&quot;b -&gt; size:&quot;, b.size)\nprint(&quot;b -&gt; dtype:&quot;, b.dtype)\n<\/pre><\/div>\n\n\n<p>Output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nb -&gt; ndim: 2\nb -&gt; shape: (2, 3)\nb -&gt; size: 6\nb -&gt; dtype: dtype(&#039;int64&#039;)\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Accessing NumPy Array Elements<\/h2>\n\n\n\n<p>Similar to accessing list elements and array elements in Python, numpy arrays are accessed in the same way.<\/p>\n\n\n\n<p>To access individual elements in multidimensional arrays, we use comma-separated indices for each dimension.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; b&#x5B;0]\narray(&#x5B;1, 2, 3])\n&gt;&gt;&gt; b&#x5B;1]\narray(&#x5B;4, 5, 6])\n&gt;&gt;&gt; b&#x5B;-1]\narray(&#x5B;4, 5, 6])\n&gt;&gt;&gt; b&#x5B;1, 1]\n5\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">NumPy Array slicing<\/h2>\n\n\n\n<p>Once again, similar to the Python standard library, NumPy also provides us with the slice operation on numpy arrays, using which we can access the array slice of elements to give us a corresponding subarray.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; b&#x5B;:]\narray(&#x5B;&#x5B;1, 2, 3],\n       &#x5B;4, 5, 6]])\n&gt;&gt;&gt; b&#x5B;:1]\narray(&#x5B;1, 2, 3])\n<\/pre><\/div>\n\n\n<p>In fact, this is the widely recommended way to use NumPy arrays, due to the highly optimized nature of the numpy operations. Since native python methods are quite slow in comparison, we should only use numpy methods to manipulate numpy arrays. Pure Python iterative loops and other list comprehensions are not used with numpy as a result.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Other ways to generate numpy arrays<\/h2>\n\n\n\n<p>We can use numpy built-in <code>arange(n)<\/code> method to construct a 1-Dimensional array consisting of the numbers <code>0<\/code> to <code>n-1<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; c = np.arange(12)\n&gt;&gt;&gt; print(c)\n&#x5B;0 1 2 3 4 5 6 7 8 9 10 11]\n&gt;&gt;&gt; c.shape\n(12,)\n<\/pre><\/div>\n\n\n<p>Using <code>random.randint(limit, size=N)<\/code> generates a random integer array with all elements between 0 and <code>limit<\/code>, and with a size of <code>N<\/code>, specified as a keyword argument.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; d = np.random.randint(10, size=6)\n&gt;&gt;&gt; d\narray(&#x5B;7, 7, 8, 8, 3, 3])\n&gt;&gt;&gt; e = np.random.randint(10, size=(3,4))\n&gt;&gt;&gt; e\narray(&#x5B;&#x5B;2, 2, 0, 5],\n       &#x5B;8, 9, 7, 3],\n       &#x5B;5, 7, 7, 0]])\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Manipulating NumPy Arrays<\/h2>\n\n\n\n<p>NumPy provides a method <code>reshape()<\/code>, which can be used to change the dimensions of the numpy array and modify the original array in place. Here, we show an illustration of using <code>reshape()<\/code> to change the shape of <code>c<\/code> to <code>(4, 3)<\/code><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; c\narray(&#x5B; 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])\n&gt;&gt;&gt; c.shape\n(12,)\n&gt;&gt;&gt; c.reshape(4, 3)\narray(&#x5B;&#x5B; 0,  1,  2],\n       &#x5B; 3,  4,  5],\n       &#x5B; 6,  7,  8],\n       &#x5B; 9, 10, 11]])\n<\/pre><\/div>\n\n\n<p>Since numpy operations are designed to be highly optimized, any subarray that is created from an array is still holding the reference to the original array. This means that if the subarray is modified in place, the original array is also modified.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; f = e&#x5B;:3, :2]\n&gt;&gt;&gt; f\narray(&#x5B;&#x5B;2, 2],\n       &#x5B;8, 9],\n       &#x5B;5, 7]])\n&gt;&gt;&gt; f&#x5B;0,0] *= 3\n&gt;&gt;&gt; f\narray(&#x5B;&#x5B;6, 2],\n       &#x5B;8, 9],\n       &#x5B;5, 7]])\n&gt;&gt;&gt; e\narray(&#x5B;&#x5B;6, 2, 0, 5],\n       &#x5B;8, 9, 7, 3],\n       &#x5B;5, 7, 7, 0]])\n<\/pre><\/div>\n\n\n<p>Here, the original array <code>e<\/code> is also modified with any change in the subarray slice <code>f<\/code>. This is because numpy slices only return a <strong>view<\/strong> of the original array.<\/p>\n\n\n\n<p>To ensure that the original array is not modified with any change in the subarray slice, we use numpy <code>copy()<\/code> method to create a copy of the array and modify the cloned object, instead of dealing with a reference of the original object. <\/p>\n\n\n\n<p>The below snippet shows how <code>copy<\/code> deals with this issue.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; e\narray(&#x5B;&#x5B;6, 2, 0, 5],\n       &#x5B;8, 9, 7, 3],\n       &#x5B;5, 7, 7, 0]])\n&gt;&gt;&gt; f = e&#x5B;:3, :2].copy()\n&gt;&gt;&gt; f\narray(&#x5B;&#x5B;6, 2],\n       &#x5B;8, 9],\n       &#x5B;5, 7]])\n&gt;&gt;&gt; f&#x5B;0,0] = 100\n&gt;&gt;&gt; f\narray(&#x5B;&#x5B;100,   2],\n       &#x5B;  8,   9],\n       &#x5B;  5,   7]])\n&gt;&gt;&gt; e\n# No change is reflected in the original array\n# We are safe!\narray(&#x5B;&#x5B;6, 2, 0, 5],\n       &#x5B;8, 9, 7, 3],\n       &#x5B;5, 7, 7, 0]])\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned about numpy arrays and some elementary operations and manipulations involving them, including their attributes, array slicing, reshaping, and copying.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<p><a href=\"https:\/\/numpy.org\/doc\/\" target=\"_blank\" aria-label=\" (opens in a new tab)\" rel=\"noreferrer noopener\" class=\"rank-math-link\">NumPy Docs<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>NumPy is the most commonly used scientific computing Python library. It provides a fast Pythonic interface, while still using the much faster C++ under the hood for computation. This ensures that the high-level readability and Pythonic features are still present while making the actual computation much faster than what pure Python code could. Here, we [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[93],"tags":[],"class_list":["post-1070","post","type-post","status-publish","format-standard","hentry","category-numpy"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/1070","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=1070"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/1070\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=1070"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=1070"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=1070"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}