Python numpy array удалить элемент

numpy.delete#

Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr[obj].

Parameters : arr array_like

obj slice, int or array of ints

Indicate indices of sub-arrays to remove along the specified axis.

Changed in version 1.19.0: Boolean indices are now treated as a mask of elements to remove, rather than being cast to the integers 0 and 1.

The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array.

Returns : out ndarray

A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.

Insert elements into an array.

Append elements at the end of an array.

Often it is preferable to use a boolean mask. For example:

>>> arr = np.arange(12) + 1 >>> mask = np.ones(len(arr), dtype=bool) >>> mask[[0,2,4]] = False >>> result = arr[mask,. ] 

Is equivalent to np.delete(arr, [0,2,4], axis=0) , but allows further use of mask.

>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) >>> arr array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) >>> np.delete(arr, 1, 0) array([[ 1, 2, 3, 4], [ 9, 10, 11, 12]]) 
>>> np.delete(arr, np.s_[::2], 1) array([[ 2, 4], [ 6, 8], [10, 12]]) >>> np.delete(arr, [1,3,5], None) array([ 1, 3, 5, 7, 8, 9, 10, 11, 12]) 

Источник

numpy.delete: How to Remove Elements from a NumPy Array

However, there is a lot more when it comes to removing elements from a NumPy array.

In this guide, you are going to learn how to:

  • Remove elements from 1D arrays.
  • Remove elements from 2D arrays.
  • Use the axis to remove entire rows/columns.
  • Remove a specific element by a value.

How Does numpy.delete() Work

In NumPy, there is a built-in function numpy.delete() you can use to remove elements from an array.

The syntax of numpy.delete() is:

numpy.delete(arr, obj, axis=None)
  • arr is the input array from which you want to remove elements.
  • obj specifies the index or indices at which you want to remove elements.
  • axis is an optional parameter that specifies the axis along which to remove the elements. By default it is None. In this case, the obj is applied to a flattened version of the arr.

The numpy.delete() function returns a copy of the original array arr.

Now that you understand how the numpy.delete() function works, let’s see common use cases for it.

1D NumPy Arrays

When it comes to removing elements, dealing with 1D arrays is easy. You do not need to worry about the axis parameter. All you need to do is to specify the index or indices at which you want to remove an element or multiple elements.

Let’s see some useful examples.

How to Remove a Single Element

To delete a single element from a 1D NumPy array:

  1. Specify the index at which you want to remove the element.
  2. Call the numpy.delete() function on the array with the specified index.

For example, let’s remove the 3rd element from an array of numbers:

import numpy as np arr = np.array([1, 2, 3, 4, 5]) arr = np.delete(arr, 2) print(arr)

Now that you handle removing single elements, let’s take a look at how you can remove multiple elements in one go.

How to Remove Multiple Elements

One way to remove multiple elements from a NumPy array is by calling the numpy.delete() function repeatedly for a bunch of indices.

However, this introduces unnecessary repetition.

The correct way to remove multiple elements is to:

  1. Add the indices to a sequence, such as a list.
  2. Call the numpy.delete() function on the array with the given index sequence.

For example, let’s remove the first, second, and third elements from an array of strings:

import numpy as np arr = np.array(["Alice", "Bob", "Charlie", "David", "Eric"]) arr = np.delete(arr, [0, 1, 2]) print(arr)

At this point, you understand how to remove elements from a 1D array.

Next, let’s move up to the 2nd dimension.

2D NumPy Arrays

Removing elements from a 2D NumPy array is almost as easy as removing elements from a 1D one.

However, when it comes to 2D arrays, you may want to remove:

  • A single element
  • Multiple elements
  • A single row
  • Multiple rows
  • A single column
  • Multiple columns

Removing columns and rows means you have to specify the optional axis parameter.

Let’s see some useful examples to support understanding.

How to Remove a Column

To delete a column from a 2D NumPy array:

  1. Specify the index of the column you want to remove.
  2. Set the axis parameter to 1.
  3. Call the numpy.delete() function with the desired column index and axis.

For example, let’s remove the 2nd column from a 2D array:

import numpy as np arr = np.array([[1 ,2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) arr = np.delete(arr, 1, axis=1) print(arr)

Now that you understand how to remove a single column, let’s take a look at how to remove multiple columns.

How to Remove Multiple Columns

One way to remove multiple columns is to repeat the process of removing one column for each column.

However, this is not the optimal way to do things.

To remove multiple columns from a 2D NumPy array:

  1. Specify all the columns you want to remove as a sequence, such as a list.
  2. Set the axis 1.
  3. Call the numpy.delete() function for the given column indexes and axis.

For example, let’s remove the first and the last column of the array of numbers:

import numpy as np arr = np.array([[1 ,2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) arr = np.delete(arr, [0,3], axis=1) print(arr)

Now you understand how to remove columns from a NumPy array. The logical next step is to learn how to remove rows.

How to Remove a Row

To delete a row from a 2D NumPy array:

  1. Specify the index of the row you want to delete.
  2. Set the axis at 0 to touch the rows.
  3. Call the numpy.delete() function on the given row index for the 0 axis.

For example, let’s remove the first row in an array of numbers:

import numpy as np arr = np.array([[1 ,2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) arr = np.delete(arr, 0, axis=0) print(arr)

Now that you understand how to remove a row from a NumPy array, let’s take a look at how to remove multiple rows at the same go.

How to Remove Multiple Rows

To delete multiple rows from a NumPy array, you could repeat the above process of removing a single row for each row you want to remove.

However, this is not the best way to do it.

To remove multiple rows from a 2D NumPy array:

  1. Specify the indices of the rows to be deleted as a sequence, such as a list.
  2. Set the axis at 0 to affect rows.
  3. Call the numpy.delete() function for the set of indices and the axis.

For example, let’s remove the first and the last row from an array of numbers.

import numpy as np arr = np.array([[1 ,2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) arr = np.delete(arr, [0, 2], axis=0) print(arr)

Now you understand how to remove rows and columns.

Last but not least, let’s take a look at how to remove a specific element from a NumPy array by value.

How to Remove a Specific NumPy Array Element by Value

Sometimes you might want to remove specific elements or elements from a NumPy array.

To remove a specific element from a NumPy array by value:

  1. Call the numpy.delete() function.
  2. Use numpy.where() function as the second argument to specify the removing criterion.

For example, let’s remove all 1s from an array of numbers:

import numpy as np arr = np.array([1, 1, 1, 1, 2, 3, 4]) arr = np.delete(arr, np.where(arr == 1)) print(arr)

Conclusion

Today you learned how to remove elements from NumPy arrays.

To recap, whenever you want to remove an element, call the numpy.delete() function for a given index.

If you are working with multidimensional arrays and want to delete entire columns/rows, specify the optional axis parameter.

For example, with 2D arrays, axis=1 affects columns, and axis=0 touches the rows.

Источник

Numpy delete() в Python: удаление подмассива из массива

Метод Python numpy.delete(array, object, axis = None) возвращает новый массив с удалением подмассивов вместе с указанной осью.

Что такое функция Numpy delete() в Python?

Функция Numpy delete() в Python используется для удаления любого подмассива из массива вместе с указанной осью. Функция numpy delete() возвращает новый массив после выполнения операции удаления. Для одномерного массива она просто удаляет объект, который мы хотим удалить.

Синтаксис

Параметры

Функция Numpy delete() принимает три параметра:

  1. array : это входной массив.
  2. object : это может быть любое число или подмассив.
  3. axis : указывает ось, которая должна быть удалена из массива.

Возвращаемое значение

Функция numpy delete() возвращает массив, удаляя подмассив, который был упомянут во время вызова функции.

Примеры программирования

Функция Python Numpy delete()

Удаление элементов из одномерного массива

В этой программе мы сначала создали одномерный массив, используя функцию numpy arange(). Затем мы напечатали исходный массив. Затем мы инициализировали значение, которое необходимо удалить из массива 1D в объектной переменной и вызвали функцию delete(), минуя объект в функции.

Обратите внимание, что мы не упомянули ось, когда вызывали функцию delete(), потому что в массиве 1D есть только одна ось, поэтому по умолчанию ось должна быть None. Однако в объекте мы дали значение 3, поэтому он удалил 3 из исходного массива, а затем вернул новый массив, который напечатали.

Python Numpy: удаление элементов из 2D-массива

Используя метод NumPy np.delete(), вы можете удалить любую строку и столбец из массива NumPy ndarray. Мы также можем удалить элементы из 2D-массива, используя функцию numpy delete(). См. следующий код.

Источник

Читайте также:  Using yield in python
Оцените статью