Numpy Arrays

An array is a matrix of values of the same type, but, indexed by a tuple of non-negative integer numbers. Rank of an array is signified by the number of dimensions while its shape is specified through a tuple which gives the number of elements along each division. In this article we would further be learning the techniques to do Numpy Array to List conversion.

Arrays in Python

How to work with ndarray in Python?

Using the following functions, arrays can be created :

  • np.ndarray(shape, type): Using this command we create an array of the specified shape with any random numbers.
  • np.array(array_object): Using this command, thus, an array with list or tuple objects
  • np.arange(range): Using this command, thus, an array with a specific range
  • np.zeros(shape): This command thus, creates an array of the specified shape with all elements being zeros.

Also, these arrays are initialized from nested Python lists, and its elements are accessed using [] brackets.

import numpy as np

c = np.array([4, 2, 1])   # rank 1 array
print(type(c))            # Prints class as arrays 
                            "<class 'numpy.ndarray'>"

# Elements can be accessed in the following way
print(c[0], c[1], c[2])   # Prints "4 2 1"
c[2] = 5                  # Changing an element in the a
print(c)                  # Prints "[4, 2, 5]"

print(c.shape)            # Prints "(3,)"

b = np.array([[4,2,3],[1,5,6]])    # rank 2 array
print(b.shape)                     # Prints "(2, 3)"

A python list, is created by placing all items (elements) inside [] brackets, separated by commas.

Lists in Python

It can also have any number of items and they may be of different types (integer, float, string, etc.)

# list of integers
my_list = [5, 2, 3]

# list with mixed data types
my_list = [5, "Hello", 5.4]

Thus, now we will see how to create a Numpy Array from a sequence like list or tuple etc. 

To install the python’s numpy module, the following command is used

pip install numpy

# The module then needs to be imported before using
import numpy as np

numpy.array()

In order, to create an array Python’s Numpy module provides a function numpy.array()

numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

Arguments:  object can be anything like a list or tuple. Other parameteric values are optional.

Thus, it returns a Numpy Array .

Create Numpy Array from a list

Thus, We pass the list object to numpy.array() to create an array from a list

np.array([9,4,8,7,3,5,6])
print('Contents of the ndArray : ')
print(npArray)
Output:
Contents of the ndArray : [9 4 8 7 3 5 6]

Checking the type of a Numpy Array object

type(npArrObject)

Example:
npArray = np.array((1,2,3,4,7))
print(type(npArray))

Output:
<class 'numpy.ndarray'

Checking data type of elements in Array object

To check the data type of Numpy Array elements we write:

print('Data Type of elements in ndArray : ')
npArray = np.array((1, 2, 3, 4, 7))
print(npArray.dtype)

Output:
int32

Creating a 1-Dimensional Array from nested lists

To create a 1-Dimensional numpy array from nested lists, we need to merge all the lists into a single list and then give it to numpy.array(). Like,

nest_Lists = [[1, 2, 3], [3, 4, 5], [6, 7, 8]]
# Creating 1-dimensional ndArray from nested lists
Array = np.array([elem for oneList in nest_Lists for elem in oneList])
print('Contents of the 1-D Array : ')
print(Array)

Output:
Contents of the 1-D Array : [1 2 3 3 4 5 6 7 8]

Creating a 2-Dimensional Array from nested lists

Let’s say, I want to create 2D Numpy Array like Matrix. Then we do the following:

# Creating 2-Dimensional array from a list of lists

npArray = np.array( [ [1, 2, 3] , [3, 4, 5] , [7, 8, 9]])
print('Contents of the ndArray : ')print(npArray)

Output:
[[1 2 3] [3 4 5] [7 8 9]]

Creating an Array from a list with different data type

The dtype can be passed as parameter in numpy.array(), also. Thus, this, converts them into a passed datatype object.

Example:

# Creating an Array of datatype float from a list 
Array = np.array([1, 2, 4, 3, 5, 6, 7, 8], dtype = float)
print('Contents of the Array : ', Array)
print('Type of the Array : ', Array.dtype)

Output:
Contents of the Array : [1.0 2.0 4.0 3.0 5.0 6.0 7.0 8.0]
Type of the Array : float64

CONCLUSION

Arrays in python is very easily converted into Lists. There are various applications for these type of conversions

We generally, use an Array when we don’t want to further change or add elements into a collection. While, we  Use Lists when we intend to change or append items in future into a collection. 

“Static” collection of elements are generally dealt with by using an Array, while, “Dynamic” collection of elements are dealt with by using a List.