删除NumPy ndarray的行和列

删除NumPy ndarray的行和列

在这篇文章中,我们将讨论如何在一个n维数组中删除指定的行和列。我们将使用numpy.delete()方法来删除这些行和列。

语法: numpy.delete(array_name, obj, axis=None)

让我们借助一些例子来讨论一下。

示例 1:

用NumPy创建一个二维数组(3行4列)并删除指定行的程序。

# importing numpy module
import numpy as np
  
# create an array with integers
# with 3 rows and 4 columns
a = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8], 
              [9, 10, 11, 12]])
print(a)
  
# delete 0 th row
data = np.delete(a, 0, 0)
print("data  after 0 th row deleted :", data)
  
# delete 1 st row
data = np.delete(a, 1, 0)
print("data  after 1 st  row deleted :", data)
  
# delete 2 nd row
data = np.delete(a, 2, 0)
print("data  after 2 nd  row deleted :", data)

输出:

删除NumPy ndarray的行和列

示例 2:

用NumPy创建一个二维数组(6行2列)并删除指定列的程序。

# importing numpy module
import numpy as np
  
# create an array with integers with
# 6 rows and 2 columns
a = np.array([[1, 2], [5, 6], [9, 10, ],
              [78, 90], [4, 89], [56, 43]])
print(a)
  
# delete 0 th column
data = np.delete(a, 0, 1)
print("data  after 0 th  column  deleted :", data)
  
# delete 1 st column
data = np.delete(a, 1, 1)
print("data  after 1 st  column  deleted :", data)

输出:

删除NumPy ndarray的行和列

示例 3:

同时删除1行和1列。

# importing numpy module
import numpy as np
  
# create an array with integers
# with 3 rows and 3 columns
a = np.array([[67, 65, 45], 
              [45, 67, 43], 
              [3, 4, 5]])
print("Original\n", a)
  
# delete 1 st row
data = np.delete(a, 0, 0)
print("data  after 1 st row   deleted :\n", data)
  
# delete 1 st column
data = np.delete(a, 0, 1)
print("data  after 1 st  column  deleted :\n", data)

输出:

删除NumPy ndarray的行和列

示例 4:

我们可以通过在obj参数中以列表形式传递行号,一次删除n个行。

语法: numpy.delete(array_name, [row1,row2,.row n], axis=None)

# importing numpy module
import numpy as np
  
# create an array with integers 
# with 3 rows and 3 columns
a = np.array([[67, 65, 45], 
              [45, 67, 43], 
              [3, 4, 5]])
print("Original\n", a)
  
# delete 1 st row and 2 nd 
# row at a time
data = np.delete(a, [0, 1], 0)
print("data  after 1 st  and 2 ns row deleted :\n", data)

输出:

删除NumPy ndarray的行和列

示例 5:

我们可以通过在obj参数中传递列号作为一个列表,一次删除n个列。

语法: numpy.delete(array_name, [column number1,column number2,.column number n], axis=None)

# importing numpy module
import numpy as np
  
# create an array with integers 
# with 3 rows and 3 columns
a = np.array([[67, 65, 45],
              [45, 67, 43], 
              [3, 4, 5]])
print("Original\n", a)
  
  
# delete 1 st column and 3 rd 
# column at a time
data = np.delete(a, [0, 2], 1)
print("data  after 1 st and 3 rd column  deleted :\n", data)

输出:

删除NumPy ndarray的行和列

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程