Python add elements to numpy array

Append/ Add an element to Numpy Array in Python (3 Ways)

In this article, we will discuss different ways to add / append single element in a numpy array by using append() or concatenate() or insert() function.

Table of Contents

Add element to Numpy Array using append()

Numpy module in python, provides a function to numpy.append() to add an element in a numpy array. We can pass the numpy array and a single value as arguments to the append() function. It doesn’t modifies the existing array, but returns a copy of the passed array with given value added to it. For example,

import numpy as np # Create a Numpy Array of integers arr = np.array([11, 2, 6, 7, 2]) # Add / Append an element at the end of a numpy array new_arr = np.append(arr, 10) print('New Array: ', new_arr) print('Original Array: ', arr)
New Array: [11 2 6 7 2 10] Original Array: [11 2 6 7 2]

The append() function created a copy of the array, then added the value 10 at the end of it and final returned it.

Читайте также:  ESTILOS CONTRASTADOS CSS3

Frequently Asked:

Add element to Numpy Array using concatenate()

Numpy module in python, provides a function numpy.concatenate() to join two or more arrays. We can use that to add single element in numpy array. But for that we need to encapsulate the single value in a sequence data structure like list and pass a tuple of array & list to the concatenate() function. For example,

import numpy as np # Create a Numpy Array of integers arr = np.array([11, 2, 6, 7, 2]) # Add / Append an element at the end of a numpy array new_arr = np.concatenate( (arr, [10] ) ) print('New Array: ', new_arr) print('Original Array: ', arr)
New Array: [11 2 6 7 2 10] Original Array: [11 2 6 7 2]

It returned a new array containing values from both sequences i.e. array and list. It didn’t modified the original array, but returned a new array containing all values from original numpy array and a single value added along with them in the end.

Add element to Numpy Array using insert()

Using numpy.insert() function in the NumPy module, we can also insert an element at the end of a numpy array. For example,
C
Output:
O

We passed three arguments to the insert() function i.e. a numpy array, index position and value to be added. It returned a copy of array arr with value added at the given index position. As in this case we wanted to add the element at the end of array, so as the index position, we passed the size of array. Therefore it added the value at the end of array.

Important point is that it did not modifies the original array, it returned a copy of the original array arr with given value added at the specified index i.e. as the end of array.

We learned about three different ways to append single element at the end of a numpy array in python.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

numpy.append#

These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.

axis int, optional

The axis along which values are appended. If axis is not given, both arr and values are flattened before use.

Returns : append ndarray

A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.

Insert elements into an array.

Delete elements from an array.

>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) array([1, 2, 3, . 7, 8, 9]) 

When axis is specified, values must have the correct shape.

>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0) Traceback (most recent call last): . ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s) 

Источник

Как добавить элементы в массив NumPy (3 примера)

Вы можете использовать следующие методы для добавления одного или нескольких элементов в массив NumPy:

Способ 1: добавить одно значение в конец массива

#append one value to end of array new_array = np.append(my_array, 15) 

Способ 2: добавить несколько значений в конец массива

#append multiple values to end of array new_array = np.append(my_array, [15, 17, 18]) 

Способ 3: вставить одно значение в определенную позицию в массиве

#insert 95 into the index position 2 new_array = np.insert (my_array, 2, 95) 

Способ 4: вставить несколько значений в определенную позицию в массиве

#insert 95 and 99 starting at index position 2 of the NumPy array new_array = np.insert (my_array, 2, [95, 99]) 

В этом руководстве объясняется, как использовать каждый метод на практике со следующим массивом NumPy:

import numpy as np #create NumPy array my_array = np.array([1, 2, 2, 3, 5, 6, 7, 10]) #view NumPy array my_array array([ 1, 2, 2, 3, 5, 6, 7, 10]) 

Пример 1: добавление одного значения в конец массива

В следующем коде показано, как использовать np.append() для добавления одного значения в конец массива NumPy:

#append one value to end of array new_array = np.append(my_array, 15) #view new array new_array array([ 1, 2, 2, 3, 5, 6, 7, 10, 15]) 

В конец массива NumPy добавлено значение 15 .

Пример 2. Добавление нескольких значений в конец массива

В следующем коде показано, как использовать np.append() для добавления нескольких значений в конец массива NumPy:

#append multiple values to end of array new_array = np.append(my_array, [15, 17, 18]) #view new array new_array array([ 1, 2, 2, 3, 5, 6, 7, 10, 15, 17, 18]) 

Значения 15 , 17 и 18 были добавлены в конец массива NumPy.

Пример 3. Вставка одного значения в определенную позицию в массиве

В следующем коде показано, как вставить одно значение в определенную позицию в массиве NumPy:

#insert 95 into the index position 2 new_array = np.insert (my_array, 2, 95) #view new array new_array array([ 1, 2, 95, 2, 3, 5, 6, 7, 10]) 

Значение 95 было вставлено в позицию индекса 2 массива NumPy.

Пример 4. Вставка нескольких значений в определенную позицию в массиве

В следующем коде показано, как вставить несколько значений, начиная с определенной позиции в массиве NumPy:

#insert 95 and 99 starting at index position 2 of the NumPy array new_array = np.insert (my_array, 2, [95, 99]) #view new array new_array array([ 1, 2, 95, 99, 2, 3, 5, 6, 7, 10]) 

Значения 95 и 99 были вставлены, начиная с позиции индекса 2 массива NumPy.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные задачи в NumPy:

Источник

numpy.insert#

Insert values along the given axis before the given indices.

Parameters : arr array_like

obj int, slice or sequence of ints

Object that defines the index or indices before which values is inserted.

Support for multiple insertions when obj is a single scalar or a sequence with one element (similar to calling insert multiple times).

values array_like

Values to insert into arr. If the type of values is different from that of arr, values is converted to the type of arr. values should be shaped so that arr[. obj. ] = values is legal.

axis int, optional

Axis along which to insert values. If axis is None then arr is flattened first.

Returns : out ndarray

A copy of arr with values inserted. Note that insert does not occur in-place: a new array is returned. If axis is None, out is a flattened array.

Append elements at the end of an array.

Join a sequence of arrays along an existing axis.

Delete elements from an array.

Note that for higher dimensional inserts obj=0 behaves very different from obj=[0] just like arr[:,0,:] = values is different from arr[:,[0],:] = values .

>>> a = np.array([[1, 1], [2, 2], [3, 3]]) >>> a array([[1, 1], [2, 2], [3, 3]]) >>> np.insert(a, 1, 5) array([1, 5, 1, . 2, 3, 3]) >>> np.insert(a, 1, 5, axis=1) array([[1, 5, 1], [2, 5, 2], [3, 5, 3]]) 

Difference between sequence and scalars:

>>> np.insert(a, [1], [[1],[2],[3]], axis=1) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1), . np.insert(a, [1], [[1],[2],[3]], axis=1)) True 
>>> b = a.flatten() >>> b array([1, 1, 2, 2, 3, 3]) >>> np.insert(b, [2, 2], [5, 6]) array([1, 1, 5, . 2, 3, 3]) 
>>> np.insert(b, slice(2, 4), [5, 6]) array([1, 1, 5, . 2, 3, 3]) 
>>> np.insert(b, [2, 2], [7.13, False]) # type casting array([1, 1, 7, . 2, 3, 3]) 
>>> x = np.arange(8).reshape(2, 4) >>> idx = (1, 3) >>> np.insert(x, idx, 999, axis=1) array([[ 0, 999, 1, 2, 999, 3], [ 4, 999, 5, 6, 999, 7]]) 

Источник

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