Welcome to the second installment of our Python NumPy series! In this segment, we delve deeper into the world of NumPy arrays in Python. We’re about to unveil the what and how of these dynamic arrays. Transitioning from the foundations we laid in the first part, brace yourself for an insightful exploration. So, let’s embark on this journey to understand the essence and creation of NumPy arrays, building upon the knowledge we’ve gathered so far.
In this section, let’s delve into the realm of NumPy arrays and master the art of crafting these potent data structures. NumPy arrays stand as the cornerstone of the library, empowering us to handle and manipulate numerical data with finesse. We’ll plunge into diverse techniques for creating NumPy arrays, revealing the expansive flexibility they bestow upon data manipulation across dimensions and shapes. So, without further ado, let’s embark on our journey to explore, create, and harness the capabilities of NumPy arrays.
NumPy provides several ways to create arrays. Here are some common methods:
To create a NumPy Array, simply pass a Python list or nested lists to the np.array() function.
In the provided program, we begin by importing the NumPy library using the line ‘import numpy as np’, enabling us to wield NumPy’s functionalities.
Next, a Python list named my_list holds values [1, 2, 3, 4, 5]. We convert this list into a NumPy array by passing it as an np.array() function argument, creating array arr.
To examine the array, we use print() to display arr, revealing contents [1, 2, 3, 4, 5]. The type() function identifies the array’s data type with print(type(arr)), showing <class ‘numpy.ndarray’>, indicating arr is a NumPy array.
We access and print the first element via print(arr[0]), yielding 1, as Python array indexing starts at 0. Similarly, print(type(arr[0])) determines the first element’s data type, displaying <class ‘numpy.int64’> for a 64-bit integer.
This program showcases NumPy array creation from a Python list and basic operations to access array elements and their data types.
In addition to Python lists, NumPy empowers us to form arrays from tuples as well. Tuples, akin to lists, possess immutability, implying their elements remain unaltered post-definition. Now, let’s delve into the process of crafting NumPy arrays out of tuples.
Here’s an example:
This program initiates by importing the NumPy library through import numpy as np. A tuple named my_tuple is established, holding values (1, 2, 3, 4, 5). For the transformation of the tuple into a NumPy array, we employ my_tuple as an argument within the np.array() function, consequently producing array arr.
NumPy empowers us to forge multi-dimensional arrays, providing the capability to depict and manipulate data across diverse dimensions. These arrays can encompass various numbers of dimensions, often labeled as axes. Now, let’s embark on the journey of crafting multi-dimensional arrays using NumPy.
We define a Python list, my_list, containing three sublists that depict rows of a matrix. To forge a multi-dimensional array from my_list, we feed it as an np.array() function argument. The outcome, array arr, symbolizes a 3×3 matrix. Creating multi-dimensional arrays in NumPy empowers us to handle intricate data structures like matrices or higher-dimensional tensors. Efficient execution of diverse operations becomes feasible. NumPy furnishes abundant functions and methods to manipulate and analyze multi-dimensional arrays, establishing it as a potent instrument for scientific computing and data analysis.
To discretize data and craft NumPy arrays featuring evenly spaced values, one can utilize the arange() function. This function generates a one-dimensional array that encompasses values within a designated interval.
Syntax:
By adjusting start, stop, and step (and optionally specifying dtype), you wield precise control over the array’s value range and spacing.
Here’s an example of creating a one-dimensional array using arange():
This instance showcases the arange() function’s usage to construct an array named arr, housing values from 1 to 9 (excluding 10), with an increment of 2. The resulting array becomes [1, 3, 5, 7, 9]. Harnessing arange()’s adaptability, we can fashion arrays with diverse setups, including tailoring start, stop, and step values. This versatility empowers us to discretize data effectively, yielding tailor-made one-dimensional arrays aligned with our precise requirements.
Here’s a second example demonstrating the arange() function with all arguments, including dtype, specified:
In this example, we import the NumPy arrays library using import numpy as np.
We use the arange() function to create an array named arr with the following arguments:
The resulting array will be [2.5, 3.0, 3.5, 4.0, …, 10.0, 10.5], where each consecutive value is incremented by 0.5.
This example illustrates the utilization of arange() to establish an array with defined start, stop, and step values. Additionally, we explicitly designate the array element data type as float. The versatile nature of the arange() function empowers us to fabricate arrays tailored to desired setups, essential for diverse numerical computations and data processing undertakings.
Within NumPy arrays, the creation of multi-dimensional arrays can be accomplished by intertwining the arange() function with the reshape() method. The arange() function generates a one-dimensional array of uniformly spaced values, while the reshape() method permits the transformation of this array into a specified multi-dimensional configuration. Join us as we delve into the process of crafting multi-dimensional arrays through this dynamic approach.
array.reshape((rows, columns))
In this instance, we initiate by importing the NumPy library via import numpy as np. Employing the arange() function, we shape a one-dimensional array housing values from 0 to 11 (inclusive), yielding [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]. Subsequently, we execute the reshape() method on the array, using (3, 4) as parameters to mold it into a 3×4 matrix. For an insight into the generated multi-dimensional array, the print() function comes into play, revealing its contents with print(arr).
In NumPy, the linspace() function is used to generate arrays with equally spaced values within a specified interval. The linspace() function takes the start and end points of the interval and the number of desired elements as arguments, and it returns an array with evenly distributed values.
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
Let’s delve into the distinct parameters of the linspace() function:
Here’s an example of using the linspace() function to create an array:
In the preceding example, we import the NumPy library through import numpy as np. By employing the linspace() function, we shape an array named arr with values evenly spaced between 0 and 10. The num parameter is configured to 20, signifying our intent for 20 elements in the resultant array. To scrutinize the array, we utilize the print() function to showcase its contents via print(arr). The outcome manifests as an array featuring 20 uniformly distributed values spanning 0 to 10. The prowess of the linspace() function emerges when there’s a necessity to craft arrays with a distinct quantity of equidistant values encompassing an interval. Its prevalence extends across numerous scientific, numerical computations, and visualization endeavors, bolstering tasks like plotting.
Within NumPy, the zeros() function finds its purpose in crafting arrays laden with zeros. This versatile function enables the definition of the array’s shape and data type. The outcome is an array primed with zero values across all its elements.
numpy.zeros(shape, dtype=float, order=’C’)
Let’s delve into the distinctive parameters of the zeros() function:
Here’s an example of using the zeros() function to create arrays of zeros:
In the Example, we incorporate the NumPy library using import numpy as np. The zeros() function steps in to craft two arrays:
arr_1d and arr_2d.
To inspect the arrays, we enlist the print() function to exhibit their content. The outcome surfaces as arrays brimming with zeros. This function proves instrumental when a preliminary array of zeros is indispensable for computations or data storage. It boasts widespread utility across scientific, numerical, and machine learning landscapes.
In the realm of NumPy, the ones() function serves the purpose of fabricating arrays enriched with ones. This versatile function enables the specification of the array’s shape and data type. The outcome takes the form of an array initialized with ones across all its elements.
The ones() function syntax is as follows:
numpy.ones(shape, dtype=float, order=’C’)
Let’s delve into the distinct parameters of the ones() function:
Here’s an example of using the ones() function to create arrays of ones:
In the above example, we import the NumPy library using import numpy as np.
We use the ones() function to create two arrays: arr_1d and arr_2d.
The ones() function is useful when you need to initialize an array with ones before performing computations or storing data.
In this second segment of our NumPy exploration, we’ve dived into the realm of multi-dimensional arrays, mastering the art of crafting arrays with diverse values. The linspace(), zeros(), and ones() functions have unveiled versatile approaches to data manipulation, providing us the tools to tailor arrays to our precise needs. As we harness these capabilities, we pave the way for enhanced numerical computations, scientific endeavors, and data analysis tasks. Stay tuned for the next installment, where we’ll continue our journey into the depths of NumPy’s dynamic functionalities. If you enjoyed the blog follow 1stepgrow.
We provide online certification in Data Science and AI, Digital Marketing, Data Analytics with a job guarantee program. For more information, contact us today!
Courses
1stepGrow
Anaconda | Jupyter Notebook | Git & GitHub (Version Control Systems) | Python Programming Language | R Programming Langauage | Linear Algebra & Statistics | ANOVA | Hypothesis Testing | Machine Learning | Data Cleaning | Data Wrangling | Feature Engineering | Exploratory Data Analytics (EDA) | ML Algorithms | Linear Regression | Logistic Regression | Decision Tree | Random Forest | Bagging & Boosting | PCA | SVM | Time Series Analysis | Natural Language Processing (NLP) | NLTK | Deep Learning | Neural Networks | Computer Vision | Reinforcement Learning | ANN | CNN | RNN | LSTM | Facebook Prophet | SQL | MongoDB | Advance Excel for Data Science | BI Tools | Tableau | Power BI | Big Data | Hadoop | Apache Spark | Azure Datalake | Cloud Deployment | AWS | GCP | AGILE & SCRUM | Data Science Capstone Projects | ML Capstone Projects | AI Capstone Projects | Domain Training | Business Analytics
WordPress | Elementor | On-Page SEO | Off-Page SEO | Technical SEO | Content SEO | SEM | PPC | Social Media Marketing | Email Marketing | Inbound Marketing | Web Analytics | Facebook Marketing | Mobile App Marketing | Content Marketing | YouTube Marketing | Google My Business (GMB) | CRM | Affiliate Marketing | Influencer Marketing | WordPress Website Development | AI in Digital Marketing | Portfolio Creation for Digital Marketing profile | Digital Marketing Capstone Projects
Jupyter Notebook | Git & GitHub | Python | Linear Algebra & Statistics | ANOVA | Hypothesis Testing | Machine Learning | Data Cleaning | Data Wrangling | Feature Engineering | Exploratory Data Analytics (EDA) | ML Algorithms | Linear Regression | Logistic Regression | Decision Tree | Random Forest | Bagging & Boosting | PCA | SVM | Time Series Analysis | Natural Language Processing (NLP) | NLTK | SQL | MongoDB | Advance Excel for Data Science | Alteryx | BI Tools | Tableau | Power BI | Big Data | Hadoop | Apache Spark | Azure Datalake | Cloud Deployment | AWS | GCP | AGILE & SCRUM | Data Analytics Capstone Projects
Anjanapura | Arekere | Basavanagudi | Basaveshwara Nagar | Begur | Bellandur | Bommanahalli | Bommasandra | BTM Layout | CV Raman Nagar | Electronic City | Girinagar | Gottigere | Hebbal | Hoodi | HSR Layout | Hulimavu | Indira Nagar | Jalahalli | Jayanagar | J. P. Nagar | Kamakshipalya | Kalyan Nagar | Kammanahalli | Kengeri | Koramangala | Kothnur | Krishnarajapuram | Kumaraswamy Layout | Lingarajapuram | Mahadevapura | Mahalakshmi Layout | Malleshwaram | Marathahalli | Mathikere | Nagarbhavi | Nandini Layout | Nayandahalli | Padmanabhanagar | Peenya | Pete Area | Rajaji Nagar | Rajarajeshwari Nagar | Ramamurthy Nagar | R. T. Nagar | Sadashivanagar | Seshadripuram | Shivajinagar | Ulsoor | Uttarahalli | Varthur | Vasanth Nagar | Vidyaranyapura | Vijayanagar | White Field | Yelahanka | Yeshwanthpur
Mumbai | Pune | Nagpur | Delhi | Gurugram | Chennai | Hyderabad | Coimbatore | Bhubaneswar | Kolkata | Indore | Jaipur and More