Friday , June 18 2021
Home / Data Science / Array Manipulation

Array Manipulation

9 – Manipulate an Array

Numpy Array Manipulation

In [2]:
import numpy as np
In [3]:
arr = np.random.randint(1,10,[3,3])
arr
Out[3]:
array([[7, 4, 7],
       [5, 3, 6],
       [2, 1, 4]])

Transpose an array

In [4]:
print(arr.T)
[[7 5 2]
 [4 3 1]
 [7 6 4]]

or

In [5]:
print(np.transpose(arr))
[[7 5 2]
 [4 3 1]
 [7 6 4]]

or

In [6]:
print(arr.transpose())
[[7 5 2]
 [4 3 1]
 [7 6 4]]

numpy.swapaxes() function interchange two axes of an array.

  • Syntax : numpy.swapaxes(arr, axis1, axis2)
In [7]:
arr1 = np.array([[2, 4, 6]])
arr1
Out[7]:
array([[2, 4, 6]])
In [8]:
np.swapaxes(arr1, 0, 1)
Out[8]:
array([[2],
       [4],
       [6]])

3D Array

In [9]:
arr1 = np.arange(16).reshape((2,2,4))
arr1
Out[9]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]]])
In [10]:
np.swapaxes(arr1, 0, 1)
Out[10]:
array([[[ 0,  1,  2,  3],
        [ 8,  9, 10, 11]],

       [[ 4,  5,  6,  7],
        [12, 13, 14, 15]]])

Change the shape of an array

In [11]:
# change the shape of an array and return a copy
arr = np.arange(12)
arr
Out[11]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
In [12]:
arr.reshape((2,6))
Out[12]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])
In [13]:
# change the shape of an array in place
arr.resize((2,6))
arr
Out[13]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])

flatten an array

In [14]:
# return a copy
arr.flatten()    
Out[14]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
In [15]:
# return a view
# change any element in the view will change the initial array
arr.ravel()      
Out[15]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

append elements to an array

In [16]:
arr = np.array([1,2,3])
In [17]:
# append a scalar and return a copy
arr1 = np.append(arr, 4)    
print(arr1)
[1 2 3 4]
In [18]:
# append an array and return a copy
arr2 = np.append(arr, [4,5,6])    
print(arr2)
[1 2 3 4 5 6]

insert elements into an array

In [19]:
# np.insert(array, position, element)

# insert a scalar at a certain position
arr3 = np.insert(arr, 0, 100)    
print(arr3)
[100   1   2   3]
In [20]:
# insert multiple values at a certain position
arr3 = np.insert(arr, 0, [1,2,3])    
print(arr3)
[1 2 3 1 2 3]

delete elements from an array

In [21]:
# remove the element at position 0
arr4 = np.delete(arr, 0)    
print(arr4)
[2 3]
In [22]:
# remove the element at multiple positions
arr4 = np.delete(arr, [0,2])    
print(arr4)
[2]

copy an array

In [23]:
arr = np.array([1,2,3])
In [24]:
# the following methods are all deep copy
arr1 = np.copy(arr)
# or 
arr1 = arr.copy()
# or 
arr1 = np.array(arr, copy=True)

About Machine Learning

Check Also

NumPy Array Sorting

8 – Sort an Array Sorting of an Array¶ In [2]: import numpy as np In [3]: …

Leave a Reply

Your email address will not be published. Required fields are marked *