{"id":88419,"date":"2023-09-29T19:00:17","date_gmt":"2023-09-29T13:30:17","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=88419"},"modified":"2023-09-29T19:00:17","modified_gmt":"2023-09-29T13:30:17","slug":"numpy-array","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/","title":{"rendered":"NumPy Array"},"content":{"rendered":"<p>NumPy is a fundamental library in Python for numerical computing. It is designed to efficiently handle large datasets and perform various mathematical operations. One of the primary reasons for its popularity is the numpy.ndarray data structure, known as a NumPy array. Unlike Python&#8217;s built-in lists, NumPy arrays offer several advantages that make them indispensable in data analysis, scientific computing, and machine learning.<\/p>\n<h2>Differences Between Python Lists and NumPy Arrays<\/h2>\n<p><strong>Memory Efficiency:<\/strong> NumPy arrays are more memory efficient compared to Python lists. This efficiency arises due to the homogeneous nature of NumPy arrays, meaning all elements are of the same data type, while lists can hold a mix of different data types.<\/p>\n<p><strong>Performance:<\/strong> NumPy arrays provide superior performance in terms of computation speed. They are implemented in C and Fortran, which allows them to take advantage of low-level optimizations, making operations significantly faster compared to Python lists.<\/p>\n<p><strong>Multidimensional Support:<\/strong> NumPy arrays are designed to handle multi-dimensional data efficiently. They can represent matrices and tensors of any size, which is crucial for scientific computing tasks.<\/p>\n<p><strong>Broadcasting:<\/strong> As mentioned earlier, NumPy arrays support broadcasting, allowing mathematical operations between arrays of different shapes and making complex computations concise and efficient.<\/p>\n<p><strong>Functionality:<\/strong> NumPy provides a vast collection of mathematical functions (ufuncs) and methods tailored for array operations. This extensive functionality simplifies complex numerical operations and data manipulation tasks.<\/p>\n<h4>Understanding numpy.array()<\/h4>\n<p>The numpy.array() function is used to create a NumPy array from a given object, such as a list or tuple. This function allows you to explicitly specify the data type of the elements in the array, along with other optional parameters for customization.<\/p>\n<h4>Syntax<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0, like=None)\n<\/pre>\n<p><strong>object:<\/strong> It signifies the input information used to generate the array. It can be an array itself, any object that exposes the array interface, an object that produces an array through its array method, or any nested sequence. If the object is a single value, a 0-dimensional array containing that value will be produced.<\/p>\n<p><strong>dtype:<\/strong> It specifies the desired data type for the array. If it is not given, NumPy will try to use a default dtype that can represent the values by applying promotion rules when required. Moreover, the data type will be inferred based on the input data.<\/p>\n<p><strong>Copy:<\/strong> It controls whether the object is copied or not. If True (default), a copy is made. Otherwise, a copy will only be made if __array__ returns a copy, if the object is a nested sequence, or if a copy is needed to satisfy other requirements like dtype or order.<\/p>\n<p><strong>Order:<\/strong> The order parameter allows you to indicate how the array&#8217;s memory arrangement should be. If the input isn&#8217;t already an array, the freshly generated array will adopt the C order (row-major) by default, unless &#8216;F&#8217; is indicated, in which case it will adhere to the Fortran order (column-major). When the input is an array, the guidelines for maintaining the order are detailed in the earlier provided table.<\/p>\n<p><strong>subok:<\/strong> When the subok parameter is set to True, sub-classes will be passed through. If it is set to False (default), the returned array will be forced to be a base-class array. This parameter is good for maintaining the characteristics of subclasses.<\/p>\n<p><strong>ndmin:<\/strong> This parameter specifies the minimum number of dimensions that the resulting array should have. Ones will be prepended to the shape according to the requirement. It is useful when you want to ensure a minimum shape for your array.<\/p>\n<p><strong>Like:<\/strong> The like parameter was introduced in NumPy version 1.20.0, it allows referencing of an object to create arrays that are not NumPy arrays. If the array-like object passed as like supports the __array_function__ protocol, the result will be defined by it. This parameter ensures the creation of an array compatible with the object passed via this argument.<\/p>\n<p>Now that we understand the key differences, let&#8217;s dive into how to work with NumPy arrays in Python!<\/p>\n<h3>Working with NumPy Arrays<\/h3>\n<h4>1. Importing NumPy<\/h4>\n<p>To start using NumPy in your Python program, you need to begin importing it.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np<\/pre>\n<h4>2. Creating NumPy Arrays<\/h4>\n<p><strong>Let&#8217;s create a basic 1-dimensional array:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\n\n# Create a 1-dimensional NumPy array\ndataflair_array = np.array([1, 2, 3, 4, 5])\nprint(dataflair_array)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>[1 2 3 4 5]<\/p>\n<h4>3. One and Multidimensional Arrays<\/h4>\n<p>Arrays are essential data structures in programming, especially for data manipulation and numerical computations. There are two primary types of arrays: one-dimensional arrays and multi-dimensional arrays.<\/p>\n<p><strong>One-Dimensional Array:<\/strong><\/p>\n<p>A one-dimensional array, often referred to as a 1D array or vector, is a linear sequence of elements. It&#8217;s like a list of values, where each value is assigned an index. One-dimensional arrays are commonly used to store data in a single row or column, making them suitable for tasks like representing time series, sensor readings, or sequences of values.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\n\none_dim_array = np.array([1, 2, 3, 4, 5])\nprint(one_dim_array[2]) \n<\/pre>\n<p><strong>Output:<\/strong> 3<\/p>\n<p><strong>Multi-Dimensional<\/strong> <strong>Array:<\/strong><\/p>\n<p>A multi-dimensional array extends the concept of a 1D array into two or more dimensions. The most common form is a 2D array, which can be thought of as a table or matrix. Multi-dimensional arrays are used to represent structured data, such as images, tables of numerical data, or grids of values.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\n\ntwo_dim_array = np.array([[1, 2, 3],\n                          [4, 5, 6],\n                          [7, 8, 9]])\nprint(two_dim_array[1, 2]) \n<\/pre>\n<p><strong>Output:<\/strong> 6<\/p>\n<p>NumPy arrays can have multiple dimensions. For example, a 2-dimensional array is like a matrix with rows and columns:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\n\n# Create a 2-dimensional NumPy array\ndataflair_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\nprint(dataflair_matrix)\n<\/pre>\n<p><strong>Output:<\/strong><br \/>\n[[1 2 3]<br \/>\n[4 5 6]<br \/>\n[7 8 9]]<\/p>\n<h4>4. Array Attributes<\/h4>\n<p>NumPy arrays have several attributes that provide useful information about the array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\n\ndataflair_array = np.array([1, 2, 3, 4, 5])\n\nprint(\"Shape:\", dataflair_array.shape)       # Shape of the array\nprint(\"Dimensions:\", dataflair_array.ndim)   # Number of dimensions\nprint(\"Size:\", dataflair_array.size)         # Total number of elements\nprint(\"Data type:\", dataflair_array.dtype)   # Data type of the elements\n\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Shape: (5,)<br \/>\nDimensions: 1<br \/>\nSize: 5<br \/>\nData type: int64<\/p>\n<h4>5. Array Indexing and Slicing<\/h4>\n<p>You can access individual elements or slices of a NumPy array using indexing and slicing:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\n\ndataflair_array = np.array([1, 2, 3, 4, 5])\n\nprint(\"First element:\", dataflair_array[0])         # Access the first element\nprint(\"Last element:\", dataflair_array[-1])         # Access the last element\nprint(\"Slicing:\", dataflair_array[1:4])             # Slice elements from index 1 to 3 (exclusive)\nprint(\"Reverse:\", dataflair_array[::-1])            # Reverse the array\n\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>First element: 1<br \/>\nLast element: 5<br \/>\nSlicing: [2 3 4]<br \/>\nReverse: [5 4 3 2 1]<\/p>\n<h4>6. Mathematical Operations<\/h4>\n<p>NumPy arrays support element-wise mathematical operations:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\n\ndataflair_array1 = np.array([1, 2, 3])\ndataflair_array2 = np.array([4, 5, 6])\n\n# Element-wise addition\nresult = dataflair_array1 + dataflair_array2\nprint(\"Addition:\", result)\n\n# Element-wise multiplication\nresult = dataflair_array1 * dataflair_array2\nprint(\"Multiplication:\", result)\n<\/pre>\n<p><strong>Output:<\/strong><br \/>\nAddition: [5 7 9]<br \/>\nMultiplication: [ 4 10 18]<\/p>\n<h4>7. Broadcasting<\/h4>\n<p>NumPy arrays support broadcasting for element-wise operations between arrays with different shapes:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\n\ndataflair_array = np.array([1, 2, 3])\n\n# Scalar multiplication (Broadcasting)\nresult = dataflair_array * 2\nprint(\"Scalar Multiplication:\", result)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Scalar Multiplication: [2 4 6]<\/p>\n<h4>8. Universal Functions (ufunc)<\/h4>\n<p>NumPy provides universal functions (ufunc) for common mathematical operations:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\n\ndataflair_array = np.array([0, np.pi \/ 2, np.pi])\n\n# Calculate sine of each element\nresult = np.sin(dataflair_array)\nprint(\"Sine:\", result)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Sine: [0.0000000e+00 1.0000000e+00 1.2246468e-16]<\/p>\n<h3>Conclusion<\/h3>\n<p>NumPy arrays are a fundamental tool for numerical computing in Python. Their memory efficiency, performance, and extensive functionality make them a top choice for handling large datasets and complex mathematical operations. As you progress in your Python journey, mastering NumPy will be invaluable in various data science and scientific computing projects. Happy coding with DataFlair and NumPy!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>NumPy is a fundamental library in Python for numerical computing. It is designed to efficiently handle large datasets and perform various mathematical operations. One of the primary reasons for its popularity is the numpy.ndarray&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":89262,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[385],"tags":[5198,412,2242,5199],"class_list":["post-88419","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-numpy-tutorials","tag-array-in-numpy","tag-numpy-array","tag-python","tag-python-numpy-array"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>NumPy Array - TechVidvan<\/title>\n<meta name=\"description\" content=\"Python journey, mastering NumPy Array will be invaluable in various data science and scientific computing projects.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/numpy-array\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"NumPy Array - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Python journey, mastering NumPy Array will be invaluable in various data science and scientific computing projects.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/numpy-array\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-09-29T13:30:17+00:00\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"NumPy Array - TechVidvan","description":"Python journey, mastering NumPy Array will be invaluable in various data science and scientific computing projects.","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:\/\/techvidvan.com\/tutorials\/numpy-array\/","og_locale":"en_US","og_type":"article","og_title":"NumPy Array - TechVidvan","og_description":"Python journey, mastering NumPy Array will be invaluable in various data science and scientific computing projects.","og_url":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-09-29T13:30:17+00:00","author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"NumPy Array","datePublished":"2023-09-29T13:30:17+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/"},"wordCount":1005,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/#primaryimage"},"thumbnailUrl":"","keywords":["array in numpy","numPy array","Python","python numPy array"],"articleSection":["NumPy Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/numpy-array\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/","url":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/","name":"NumPy Array - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/#primaryimage"},"thumbnailUrl":"","datePublished":"2023-09-29T13:30:17+00:00","description":"Python journey, mastering NumPy Array will be invaluable in various data science and scientific computing projects.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/numpy-array\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"NumPy Array"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88419","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=88419"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88419\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=88419"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=88419"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=88419"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}