NumPy is the best python package for array creation and manipulation. Thus, it allows you to complex mathematical calculations easily over the array. Let’s say you have a multi-dimensional array and want to delete the entire column then how you can do so. In this tutorial you will know how to delete a NumPy column with steps.
Steps to Delete a NumPy Column
Let’s know all the steps you will follow to delete a NumPy column. Just follow the steps for quick understanding.
Step 1: Import the requires libraries
The first step is to import the required libraries for the tutorial. In this tutorial I am using the NumPy package only so let’s import it using the import stamen.
import numpy as np
Step 2: Create sample numpy array
The next step is to create a dummy NumPy array that will be used for the example demonstrated here. You can create the NumPy array using the numpy.array() function. Use the below lines of code to create a sample array.
numpy_array_2d = np.array([[100, 200, 300], [400, 500, 600], [700, 800, 900]])
Step 3: Determine the index of the column
The third step is to determine which column you want to delete from the NumPy array. I will use the index to determine the column. Let’s say I want to delete the second column then the index will be 1 for deletion.
Let’s store the index of the column you want to delete in a variable.
index_column = 1;
Step 4: Delete a Numpy Column using numpy.delete() function
You have an array as well as the index of the column you want to delete. Now you will use the numpy.delete() function and pass all the required arguments like the input array, column index and axis =1 to delecolumne colun.
Add the below lines of code to delte the column.
array_after_deletion = np.delete(numpy_array_2d, index_column , axis=1)
Step 5: Display the final array
After deleting the column from the numpy array lets display the final array. You will use the print() function.
Add the below line of code.
import numpy as np numpy_array_2d = np.array([[100, 200, 300], [400, 500, 600], [700, 800, 900]]) index_column = 1; array_after_deletion = np.delete(numpy_array_2d, index_column , axis=1) print(array_after_deletion)
You can easily delete the columns from two-dimensional array using the numpy.delete() function. In this tutorial you will learn how to create a two-dimensional NumPy array and use the function to remove or delete the columns.
I hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.