Creating a NumPy Array Using Existing Data

PythonPythonBeginner
Practice Now

Introduction

NumPy is a popular Python Library that provides support for Arrays. It provides various ways to create an array from the existing data. In this lab, we will learn how to create an array using existing data.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) numpy(("`NumPy`")) -.-> numpy/IndexingandSlicingGroup(["`Indexing and Slicing`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/AdvancedTopicsGroup -.-> python/iterators("`Iterators`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") numpy/IndexingandSlicingGroup -.-> numpy/bool_idx("`Boolean Indexing`") numpy/IndexingandSlicingGroup -.-> numpy/fancy_idx("`Fancy Indexing`") subgraph Lab Skills python/comments -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} python/variables_data_types -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} python/numeric_types -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} python/lists -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} python/tuples -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} python/importing_modules -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} python/iterators -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} python/data_collections -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} python/numerical_computing -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} python/build_in_functions -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} numpy/bool_idx -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} numpy/fancy_idx -.-> lab-86398{{"`Creating a NumPy Array Using Existing Data`"}} end

Creating Array using Tuple - Using numpy.asarray

The numpy.asarray routine is used for converting the Python sequence into an ndarray. Let's create an array using a tuple using numpy.asarray.

import numpy as np

## python tuple
l = (34,7,8,78)
## creating array using the tuple
a = np.asarray(l)

print(type(a))
print(a)

Output:

<class 'numpy.ndarray'>
[34 7 8 78]

In the code above, we created an array using numpy.asarray() function by passing tuple l as input and store the returned array in variable a. The output shows that a is a numpy.ndarray.

Creating Array Using List - Using numpy.asarray

Now, we will create an array using more than one list.

import numpy as np

## python list
l = [[1,2,3],[8,9],[5,7]]
## creating array from list
b = np.asarray(l)

print(type(b))
print(b)

Output:

<class 'numpy.ndarray'>
[list([1, 2, 3]) list([8, 9]) list([5, 7])]

In the code above, we created an array using numpy.asarray() function by passing list l as input and store the returned array in variable b. The output shows that the array contains lists as elements rather than individual elements.

Creating Array Using numpy.frombuffer

The numpy.frombuffer routine is used to create an array by using the specified buffer.

import numpy as np

## intialize bytes
l = b'StudyTonight!'
print(type(l))

a = np.frombuffer(l, dtype = "S1")
print(a)
print(type(a))

Output:

<class 'bytes'>
[b'S' b't' b'u' b'd' b'y' b'T' b'o' b'n' b'i' b'g' b'h' b't' b'!']
<class 'numpy.ndarray'>

In the code above we created an array using numpy.frombuffer routine where we initialized the bytes and returned a one-dimensional array of type 'S1'. Upon execution, this function outputs all the individual characters in the given byte string.

Creating Array Using numpy.fromiter

The numpy.fromiter routine is used to create an ndarray by using an iterable object.

import numpy as np

## using python tuple
tup = (2,4,6,20)
## create an iterator
it = iter(tup)

## create ndarray using the iterator
x = np.fromiter(it, dtype = float)

print(x)
print(type(x))

Output:

[ 2. 4. 6. 20.]
<class 'numpy.ndarray'>

In the code above, we first created a Tuple tup and then created an iterator using the same. We then used that iterator to create the numpy array of floats.

Summary

In this lab, we learned different ways to create an array using existing data in NumPy library. We used different library routines to create arrays using Tuples, Lists, From Buffer, and From Iter. With these methods, we can easily create a NumPy array using the data we have and apply further analysis, computations, and operations on it.

Other Python Tutorials you may like