【NumPy】配列の行と列を削除する方法
numpy.delete() 関数またはマスク操作を使って、配列の特定の行や列を削除 できます。
numpy.delete()
numpy.delete() を使うと配列の行や列を削除できます。
numpy.delete(arr, object, axis=None)
行を削除する場合は axis=0 を指定します。
# NUMPY_DELETE
# In[1]
import numpy as np
#配列xを定義
x = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 配列xの2行目を削除
y = np.delete(x, 1, axis=0)
print(y)
# [[1 2 3]
# [7 8 9]]
列を削除する場合は axis に 1 を渡します。
# In[2]
# 配列xの3列目を削除
z = np.delete(x, 2, axis=1)
print(z)
# [[1 2]
# [4 5]
# [7 8]]
obj にリストやタプルなどの イテラブル を渡して、複数の行や列をまとめて削除することもできます。
# In[3]
#配列xを定義
x = np.array([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]])
# 配列xの1行目と3行目を削除
y = np.delete(x, [0, 2], axis = 0)
print(y)
# [[2 2 2 2]
# [4 4 4 4]]
第 3 引数 axis を省略すると、対象配列は 1 次元配列に変更され、第 2 引数 obj で指定したインデックスの要素を削除します。
# In[4]
#配列xを定義
x = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 配列xを1次元配列に変更して4番目の要素を削除
y = np.delete(x, 3)
print(y)
# [1 2 3 5 6 7 8 9]
マスク操作による行・列の削除
マスク操作 を使って特定の行や列を削除することもできます。
# NUMPY_DELETE_MASK
# In[1]
#配列xを定義
x = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# ブール配列[True True True]
mask = np.ones(len(x), dtype=bool)
# maskの2番目のTrueをFalseに変更
mask[1] = False
# xの2行目を削除
x2 = x[mask]
print(x2)
# [[1 2 3]
# [7 8 9]]
numpy.delete() is a function in the NumPy library that is used to remove elements from an array along the specified axis.
The function has the following syntax: numpy.delete(arr, obj, axis=None)
・arr is the array on which the deletion operation is performed.
・obj specifies the index or slice of elements to be deleted. It can be an integer or a slice object indicating the position of elements to be deleted.
・axis specifies the axis along which the deletion is performed. If this parameter is not specified, the array is flattened, and the specified elements are deleted.
The numpy.delete() function modifies the original array instead of creating a new array. If you want to create a new array with the specified elements removed, you need to assign the return value to a variable.