Python numpy array добавление элемента

np.append() — How To Use NumPy Append in Python

The NumPy programming library is considered to be a best-of-breed solution for numerical computing in Python.

NumPy stands out for its array data structure. NumPy arrays are excellent for handling ordered data. Moreover, they allow you to easily perform operations on every element of th array — which would require a loop if you were using a normal Python list.

One of the core capabilities available to NumPy arrays is the append method. In this tutorial, I will explain how to use the NumPy append method to add data to a NumPy array.

You can skip to a specific section of this tutorial using the table of contents below:

This tutorial makes extensive use of the NumPy package for Python. Accordingly, let’s start by importing NumPy into our development environment

You can import NumPy under the alias np (which is standard convention) with the following command:

If you’ve never used NumPy before, you might be wondering why we import the package under the np alias.

It’s because it makes it much easier to reference the package later in our program.

Instead of calling objects and methods from numpy with the dot operator, we can simply call them from np instead.

If this is not clear, do not worry. We will see plenty of examples of this later in this tutorial.

To understand how to use the np.append method, you first need to understand what a NumPy array is.

NumPy arrays are the main data structure available in the NumPy package. They are similar to normal Python lists, but come with additional functionality.

There are a few different ways that programmers can create NumPy arrays, but the most common is to pass a Python list into the np.array method.

import numpy as np my_list = [1, 4, 9, 16] my_array = np.array(my_list)

You could also pass the list into the np.array method in a single command, like this:

import numpy as np my_array = np.array([1, 4, 9, 16])

Here’s what the my_array object looks like if you print it to the Python console:

The array() notation indicates that this is indeed a NumPy array.

How to Use the NumPy Append Method

Now that you have an understanding of how to create a NumPy array, let’s learn about the np.append method.

Читайте также:  Java list add new object

The append method is used to add a new element to the end of a NumPy array. It accepts two parameters:

  • arr : the array that you’d like to append the new value to.
  • values : the value (or values) that you’d like to append to arr .

Let’s consider a few examples to see how the np.append method works in practice.

First, consider the following NumPy array:

first_array = np.array([1, 2, 3])

This NumPy array contains the integers from 1 to 3 , inclusive. Let’s add 4 to the end of this array using the np.append method:

The np.append method actually returns the value of the new array. In this case, here is the output:

In most cases, you will want to store the new array in another variable. This is done like any other variable assignment: using the = assignment operator.

second_array = np.append(first_array, 4)

You can then reference second_array later in your program, perhaps by using the various NumPy methods and operations that come included in the numerical computing package.

How to Append Two NumPy Arrays Together Using np.append

One of the more common use cases of the np.append method is to join two (or more) NumPy arrays together. This section of this tutorial will demonstrate this capability.

For illustration’s sake, we will be using the following NumPy arrays;

array1 = np.array([1,2,3]) array2 = np.array([4,5,6])

Here’s how you would append array2 to the end of array1 using the np.append method:

Here is what the output of this code looks like:

Similarly, if you wanted to append array1 to the end of the array1 , here’s how you would do it:

In this case, here’s the output:

It is even possible to append more than three arrays together using np.append . To demonstrate this, I will be using the following 3 arrays:

array1 = np.array([1,2,3]) array2 = np.array([4,5,6]) array3 = np.array([7,8,9])

You might think that the following code will properly append the three NumPy arrays together:

np.append(array1, array2, array3)

However, this results in the following error:

TypeError: only integer scalar arrays can be converted to a scalar index

To append more than two NumPy arrays together using np.append , you must wrap all but the first array in a Python list.

Here is how we would properly append array2 and array3 to array1 using np.append :

np.append(array1, [array2, array3])

Here is the output of this code:

For a more extreme example, here’s how you would append array2 and array3 twice to the end of array1 :

np.append(array1, [array2, array2, array3, array3])

And here is the output of this code:

array([1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9, 7, 8, 9])

In this tutorial, you learned how to use the np.append method available in the NumPy numerical computing library. You also learned how to append multiple NumPy arrays using np.append .

Читайте также:  Javascript web development course

If you have any other tutorials that you’d like me to write, please email me. I look forward to hearing from you!

If you enjoyed this article, be sure to join my Developer Monthly newsletter, where I send out the latest news from the world of Python and JavaScript:

Источник

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

Источник

Читайте также:  What is super constructor in java

Как добавить элементы в массив 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:

Источник

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