Python numpy очистить массив

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 из исходного массива, а затем вернул новый массив, который напечатали.

Читайте также:  Увеличение при наведении javascript

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

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

Источник

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]) 

Источник

How to remove elements from a numpy array?

In this tutorial, we will look at how to remove elements from a numpy array based on their index with the help of simple examples.

Delete specific elements from numpy array

Remove elements from numpy array

You can use the np.delete() function to remove specific elements from a numpy array based on their index. The following is the syntax:

import numpy as np # arr is a numpy array # remove element at a specific index arr_new = np.delete(arr, i) # remove multiple elements based on index arr_new = np.delete(arr, [i,j,k])

Note that, technically, numpy arrays are immutable. That is, you cannot change them once they are created. The np.delete() function returns a copy of the original array with the specific element deleted.

Let’s look at some examples to clearly see this in action –

Remove element from array on index

Pass the array and the index of the element that you want to delete.

import numpy as np # create a numpy array arr = np.array([1, 3, 4, 2, 5]) # remove element at index 2 arr_new = np.delete(arr, 2) # display the arrays print("Original array:", arr) print("After deletion:", arr_new)
Original array: [1 3 4 2 5] After deletion: [1 3 2 5]

Here, we created a one-dimensional numpy array and then removed the element at index 2 (that is, the third element in the array, 4). We see that the returned array does not have 4.

Let’s see if the returned array object is the same as the original array.

# show memory location of arr print("Original array:", id(arr)) # show memory location of arr_new print("Returned array:", id(arr_new))
Original array: 1931568517328 Returned array: 1931564130016

We can see that the original array and the returned array from the np.delete() point to different locations, that is, they are both different objects. This implies that the original array was not technically modified and rather a copy of the original array with the element deleted was returned.

Remove multiple elements based on index

You can remove multiple elements from the array based on their indexes. For this, pass the indexes of elements to be deleted as a list to the np.delete() function.

# remove element at index 2, 4 arr_new = np.delete(arr, [2, 4]) # display the arrays print("Original array:", arr) print("After deletion:", arr_new)
Original array: [1 3 4 2 5] After deletion: [1 3 2]

Here, we removed elements at index 2 and 4 from the original array. See that the returned array doesn’t have elements 4 and 5 which are present at indexes 2 and 4 in the original array respectively.

Remove elements based on condition

Another important use case of removing elements from a numpy array is removing elements based on a condition. Use np.where() to get the indexes of elements to remove based on the required condition(s) and then pass it to the np.delete() function.

# create a numpy array arr = np.array([1, 3, 4, 2, 5]) # remove all even elements from the array arr_new = np.delete(arr, np.where(arr%2 == 0)) # display the arrays print("Original array:", arr) print("After deletion:", arr_new)
Original array: [1 3 4 2 5] After deletion: [1 3 5]

Here we removed all the even elements from the original array using np.where() and np.delete() .

For more on the np.delete() function, refer to its documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • How to sort a Numpy Array?
  • Create Pandas DataFrame from a Numpy Array
  • Different ways to Create NumPy Arrays
  • Convert Numpy array to a List – With Examples
  • Append Values to a Numpy Array
  • Find Index of Element in Numpy Array
  • Read CSV file as NumPy Array
  • Filter a Numpy Array – With Examples
  • Python – Randomly select value from a list
  • Numpy – Sum of Values in Array
  • Numpy – Elementwise sum of two arrays
  • Numpy – Elementwise multiplication of two arrays
  • Using the numpy linspace() method
  • Using numpy vstack() to vertically stack arrays
  • Numpy logspace() – Usage and Examples
  • Using the numpy arange() method
  • Using numpy hstack() to horizontally stack arrays
  • Trim zeros from a numpy array in Python
  • Get unique values and counts in a numpy array
  • Horizontally split numpy array with hsplit()

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Источник

NumPy: numpy.delete() function

The numpy.delete() function is used to remove one or more elements from an array along a specified axis. For a one dimensional array, this returns those entries not returned by arr[obj].

The numpy.delete() function can be used for various purposes such as removing duplicates,

numpy.delete(arr, obj, axis=None)

NumPy manipulation: delete() function

Name Description Required /
Optional
arr Input array. Required
obj Indicate which sub-arrays to remove. Required
axis The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array. Optional

Return value:

[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.

Example: Title: Deleting a row from a numpy array using numpy.delete()

>>> import numpy as np >>> arr = np.array([[0,1,2], [4,5,6], [7,8,9]]) >>> arr array([[0, 1, 2], [4, 5, 6], [7, 8, 9]]) >>> np.delete(arr, 1, 0) array([[0, 1, 2], [7, 8, 9]]) 

In the above code, a 2-dimensional numpy array ‘arr’ is created with 3 rows and 3 columns. Then, ‘arr’ is printed to the console to verify its contents.
Next, the np.delete() function is used to remove the second row (index 1) from arr by specifying 1 as the index to be deleted and 0 as the axis along which to delete (i.e., the row axis). The resulting array with the second row removed is returned and printed to the console.

Pictorial Presentation:

NumPy manipulation: delete() function

Example: Removing rows and columns using numpy.delete()

>>> import numpy as np >>> np.delete(arr, np.s_[::2], 1) array([[1], [5], [8]]) >>> np.delete(arr, [1, 2, 5], None) array([0, 4, 5, 7, 8, 9]) 

In the first example, np.delete(arr, np.s_[::2], 1) removes every other column (starting from 0) from the arr array using the slice object np.s_[::2] as the second argument, and 1 as the third argument indicating that the operation is performed along the columns. The resulting array has only one column.
In the second example, np.delete(arr, [1, 2, 5], None) removes the elements with indices 1, 2, and 5 from the arr array along both rows and columns because the None argument is used for the second argument, which means the operation is performed on the flattened array. The resulting array is a one-dimensional array containing the remaining elements.

Pictorial Presentation:

NumPy manipulation: delete() function

Python — NumPy Code Editor:

Previous: repeat()
Next: insert()

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Оцените статью