How To Create 2-D NumPy Array List of Lists

Today we are going to learn how to create a 2-D array using the NumPy library. So let us start our program:

#We can create a 2-D array using lists

We can pass the list to the array function and this will create an array using this list.

#Example

import numpy as np
lists = [[0,1,2], [3,4,5], [6,7,8]]
array_one = np.array(lists)
print("Two Dimensional Array:",array_one)
print("Two Dimensional Array Shape:",array_one.shape)

Output

Two Dimensional Array: 
 [[0 1 2]
 [3 4 5]
 [6 7 8]]
Two Dimensional Array Shape: (3, 3)

We can pass the datatype as second argument and can create a float 2-D array.

We can pass any datatype like : ‘float’, ‘int’, ‘bool’, ‘str’ and ‘object’

Example :

import numpy as np
array_two = np.array(lists, dtype='float')
print("Two Dimensional Array Float:",array_two)
print("Two Dimensional Array Float shape:",array_two.shape)

output

Two Dimensional Array Float: 
 [[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]]
Two Dimensional Array Float shape: (3, 3)

We can Convert the datatype of each elemement to ‘int’ using astype() function

We can convert to str also by passing str

#Example :

print("Convert to Int",array_two.astype('int'))

Output

Convert to Int 
 [[0 1 2]
 [3 4 5]
 [6 7 8]]

#Example :

print("Convert to str",array_two.astype('str'))

output:

Convert to str 
 [['0.0' '1.0' '2.0']
 ['3.0' '4.0' '5.0']
 ['6.0' '7.0' '8.0']]