Modify Array Columns

MEDIUM

You are given a 2D NumPy array and a new column's data (as another 1D NumPy array or list). Describe and implement how you would:

  1. Delete the second column (index 1) of the original NumPy array.
  2. Insert the new column's data in place of the deleted second column (i.e., as the new second column, index 1).

Discuss different ways to achieve this, considering potential issues like shape compatibility.

Example:

Original Array:

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

New Column Data:

new_column = np.array([10, 11, 12])

Expected Result:

# After deleting column at index 1 and inserting new_column at index 1
result_arr = np.array([[ 1, 10,  3],
                      [ 4, 11,  6],
                      [ 7, 12,  9]])

Constraints:

  • The original array will be a 2D NumPy array.
  • The new column data will have a length matching the number of rows in the original array.

Function Signature (Python):

import numpy as np
from typing import List, Union

class Solution:
    def modify_column(self, 
                        original_arr: np.ndarray, 
                        new_column_data: Union[np.ndarray, List]) -> np.ndarray:
        # Your code here
        pass

 

Nerchuko Academy · Free DS Interview Prep