w3resource

NumPy: Remove a specific column from a given array

NumPy: Array Object Exercise-200 with Solution

Write a NumPy program to remove a specific column from a given array.

Sample Solution:

Python Code:

import numpy as np 
nums = np.random.random((7, 5))
print("Original array:")
print(nums)
print("\nDelete the first column of the said array:")
print(np.delete(nums, [0], axis=1))
print("\nDelete the last column of the said array:")
print(np.delete(nums, [4], axis=1))

Sample Output:

Original array:
[[0.54420704 0.35710194 0.79167579 0.72249474 0.99968936]
 [0.22306352 0.31085825 0.09849254 0.11708716 0.45757945]
 [0.19381592 0.13587749 0.90455038 0.95146017 0.55716851]
 [0.62031347 0.84275698 0.84665943 0.06562172 0.58415968]
 [0.41903059 0.0660559  0.85270403 0.94184265 0.95371587]
 [0.02577681 0.91577282 0.1969686  0.3472482  0.23337827]
 [0.43563908 0.62308811 0.09606371 0.79053989 0.69382428]]

Delete the first column of the said array:
[[0.35710194 0.79167579 0.72249474 0.99968936]
 [0.31085825 0.09849254 0.11708716 0.45757945]
 [0.13587749 0.90455038 0.95146017 0.55716851]
 [0.84275698 0.84665943 0.06562172 0.58415968]
 [0.0660559  0.85270403 0.94184265 0.95371587]
 [0.91577282 0.1969686  0.3472482  0.23337827]
 [0.62308811 0.09606371 0.79053989 0.69382428]]

Delete the last column of the said array:
[[0.54420704 0.35710194 0.79167579 0.72249474]
 [0.22306352 0.31085825 0.09849254 0.11708716]
 [0.19381592 0.13587749 0.90455038 0.95146017]
 [0.62031347 0.84275698 0.84665943 0.06562172]
 [0.41903059 0.0660559  0.85270403 0.94184265]
 [0.02577681 0.91577282 0.1969686  0.3472482 ]
 [0.43563908 0.62308811 0.09606371 0.79053989]]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to create an array using scientific notation numbers. Set the precision value to 6 and print the array.
Next: Write a NumPy program to create a 90x30 array filled with random point numbers, increase the number of items (10 edge elements) shown by the print statement.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}