Search
ubuntuversion array

Creating array ( array() function )

by using array() functione, you can create array object in NumPy known as ndarray object

  • shape()
  • size()
  • len()

Creating N-dimensional array

Example : One Element

In [46]:
# Just one element

import numpy as np

# Creating an array with one element
arr1 = np.array(42)

print("Show array :" , arr1)
Show array : 42

Example : 1-dimensional array

In [47]:
# One arraye

import numpy as np

# Creating 1-dimensional array 
arr2 = np.array([4, 40, 400, 4000, 40000])

print("Array :", arr2)
Array : [    4    40   400  4000 40000]

Example : 2-dimensional array

In [48]:
# 2 arrays

import numpy as np

# Creating 2-dimensional array 
arr3 = np.array([ [4, 40, 400], [5, 500, 5000] ])

print("Array :", arr3)
Array : [[   4   40  400]
 [   5  500 5000]]

Example : 3-dimensional array

In [49]:
# 3 arrays

import numpy as np

arr4 = np.array([ [4, 40, 400], [5, 50, 500], [6, 60, 600] ])

print("Array :", arr4)
Array : [[  4  40 400]
 [  5  50 500]
 [  6  60 600]]

Example : Checking the number of dimensions & corresponding elements

In [50]:
# Shape of an array

# Array with 3 dimensions , 4 elements in each dimension

import numpy as np

arr5 = np.array([ [1, 2, 3, 7], [4, 5, 6, 7], [7, 8, 9,10] ])
arr5.shape
Out[50]:
(3, 4)

Example : Checking the number of all elements with size()

In [51]:
import numpy as np

arr5 = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])

# size() : number of all elements
print("Number of all elements", arr5.size)
Number of all elements 9

Example : Checking the size of the first dimension with len()

In [52]:
import numpy as np

arr5 = np.array([ [1, 2, 3], [4, 5, 6, 8], [7, 8, 9, 5, 2] ])

# len() : returns the size of the first dimension
print("The size of the first dimension is", len(arr5))
The size of the first dimension is 3