Удаление элементов матрицы питон

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() в Python: удаление подмассива из массива

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

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

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

Читайте также:  Java io stringreader source code

Синтаксис

Параметры

Функция 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(). См. следующий код.

Источник

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:

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

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.

Читайте также:  Forum showthread php threadid

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() .

Читайте также:  Sql to csv on php

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

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

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