Numpy python сложить два массива

Как объединить массивы в Python (с примерами)

Самый простой способ объединить массивы в Python — использовать функцию numpy.concatenate , которая использует следующий синтаксис:

numpy.concatenate ((a1, a2, ….), ось = 0)

  • a1, a2…: последовательность массивов
  • ось: ось, вдоль которой будут соединяться массивы. По умолчанию 0.

В этом руководстве представлено несколько примеров использования этой функции на практике.

Пример 1: объединение двух массивов

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

import numpy as np #create two arrays arr1 = np.array([1, 2, 3, 4, 5]) arr2 = np.array([6, 7, 8]) #concatentate the two arrays np.concatenate ((arr1, arr2)) [1, 2, 3, 4, 5, 6, 7, 8] 

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

import numpy as np #create two arrays arr1 = np.array([[3, 5], [9, 9], [12, 15]]) arr2 = np.array([[4, 0]]) #concatentate the two arrays np.concatenate ((arr1, arr2), axis= 0 ) array([[3, 5], [9, 9], [12, 15], [4, 0]]) #concatentate the two arrays and flatten the result np.concatenate ((arr1, arr2), axis= None ) array([3, 5, 9, 9, 12, 15, 4, 0]) 

Пример 2. Объединение более двух массивов

Мы можем использовать аналогичный код для объединения более двух массивов:

import numpy as np #create four arrays arr1 = np.array([[3, 5], [9, 9], [12, 15]]) arr2 = np.array([[4, 0]]) arr3 = np.array([[1, 1]]) arr4 = np.array([[8, 8]]) #concatentate all the arrays np.concatenate ((arr1, arr2, arr3, arr4), axis= 0 ) array([[3, 5], [9, 9], [12, 15], [4, 0], [1, 1], [8, 8]]) #concatentate all the arrays and flatten the result np.concatenate ((arr1, arr2, arr3, arr4), axis= None ) array([3, 5, 9, 9, 12, 15, 4, 0, 1, 1, 8, 8]) 

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

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

Читайте также:  font

Источник

Numpy – Elementwise sum of two arrays

In this tutorial, we will look at how to get a numpy array resulting from the elementwise sum of two numpy arrays of the same dimensions.

Add two numpy arrays

Elementwise sum of a 2d numpy array

You can use the numpy np.add() function to get the elementwise sum of two numpy arrays. The + operator can also be used as a shorthand for applying np.add() on numpy arrays. 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 # x1 and x2 are numpy arrays of same dimensions # using np.add() x3 = np.add(x1, x2) # using + operator x3 = x1 + x2

It returns a numpy array resulting from the elementwise addition of each array value.

Let’s look at some examples of adding numpy arrays elementwise –

Add two 1d arrays elementwise

To elementwise add two 1d arrays, pass the two arrays as arguments to the np.add() function. Let’s show this with an example.

import numpy as np # create numpy arrays x1 and x2 x1 = np.array([1, 3, 0, 7]) x2 = np.array([2, 0, 1, 1]) # elementwise sum with np.add() x3 = np.add(x1, x2) # display the arrays print("x1:", x1) print("x2:", x2) print("x3:", x3)
x1: [1 3 0 7] x2: [2 0 1 1] x3: [3 3 1 8]

The array x3 is the result of the elementwise summation of values in the arrays x1 and x2.

Alternatively, you can also use the + operator to add numpy arrays elementwise.

# elementwise sum with + operator x3 = x1 + x2 # display the arrays print("x1:", x1) print("x2:", x2) print("x3:", x3)
x1: [1 3 0 7] x2: [2 0 1 1] x3: [3 3 1 8]

You can see that we get the same results as above with x3 as the array resulting from the elementwise sum of arrays x1 and x2.

Add two 2d arrays elementwise

The syntax for adding higher-dimensional arrays is also the same. Pass the two arrays to the np.add() function which then returns a numpy array resulting from elementwise addition of the values in the passed arrays.

# create 2d arrays x1 and x2 x1 = np.array([[1, 0, 1], [2, 1, 1], [3, 0, 3]]) x2 = np.array([[2, 2, 0], [1, 0, 1], [0, 1, 0]]) # elementwise sum with np.add() x3 = np.add(x1, x2) # display the arrays print("x1:\n", x1) print("x2:\n", x2) print("x3:\n", x3)
x1: [[1 0 1] [2 1 1] [3 0 3]] x2: [[2 2 0] [1 0 1] [0 1 0]] x3: [[3 2 1] [3 1 2] [3 1 3]]

Here, we add two 3×3 numpy arrays. The values in the array x3 are the result of the elementwise sum of values in the arrays x1 and x2.

Again, you can also use the + operator to perform the same operation.

# elementwise sum with + opeartor x3 = np.add(x1, x2) # display the arrays print("x1:\n", x1) print("x2:\n", x2) print("x3:\n", x3)
x1: [[1 0 1] [2 1 1] [3 0 3]] x2: [[2 2 0] [1 0 1] [0 1 0]] x3: [[3 2 1] [3 1 2] [3 1 3]]

Add more than two arrays elementwise

You can use the + operator to add (elementwise) more than two arrays as well. For example, let’s add three 1d arrays elementwise.

# create numpy arrays x1, x2, and x3 x1 = np.array([1, 3, 0, 7]) x2 = np.array([2, 0, 1, 1]) x3 = np.array([0, 1, 3, 1]) # elementwise sum with + x4 = x1+x2+x3 # display the arrays print("x1:", x1) print("x2:", x2) print("x3:", x3) print("x4:", x4)
x1: [1 3 0 7] x2: [2 0 1 1] x3: [0 1 3 1] x4: [3 4 4 9]

Here, the array x4 is the result of the elementwise sum of the arrays x1, x2, and x3.

What if the arrays have different dimensions?

# add two arrays with different dimensions x1 = np.array([1, 3, 0, 7]) x2 = np.array([2, 0, 1, 1, 1]) x3 = np.add(x1, x2)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) in 2 x1 = np.array([1, 3, 0, 7]) 3 x2 = np.array([2, 0, 1, 1, 1]) ----> 4 x3 = np.add(x1, x2) ValueError: operands could not be broadcast together with shapes (4,) (5,)

Trying to add two numpy arrays of different dimensions results in an error. This is because it doesn’t make sense to elementwise add two arrays that don’t have the same dimensions.

For more on the numpy np.add() 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.

Источник

numpy.concatenate#

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

axis int, optional

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

out ndarray, optional

If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.

dtype str or dtype

If provided, the destination array will have this dtype. Cannot be provided together with out.

Controls what kind of data casting may occur. Defaults to ‘same_kind’.

Concatenate function that preserves input masks.

Split an array into multiple sub-arrays of equal or near-equal size.

Split array into a list of multiple sub-arrays of equal size.

Split array into multiple sub-arrays horizontally (column wise).

Split array into multiple sub-arrays vertically (row wise).

Split array into multiple sub-arrays along the 3rd axis (depth).

Stack a sequence of arrays along a new axis.

Assemble arrays from blocks.

Stack arrays in sequence horizontally (column wise).

Stack arrays in sequence vertically (row wise).

Stack arrays in sequence depth wise (along third dimension).

Stack 1-D arrays as columns into a 2-D array.

When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are not preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead.

>>> a = np.array([[1, 2], [3, 4]]) >>> b = np.array([[5, 6]]) >>> np.concatenate((a, b), axis=0) array([[1, 2], [3, 4], [5, 6]]) >>> np.concatenate((a, b.T), axis=1) array([[1, 2, 5], [3, 4, 6]]) >>> np.concatenate((a, b), axis=None) array([1, 2, 3, 4, 5, 6]) 

This function will not preserve masking of MaskedArray inputs.

>>> a = np.ma.arange(3) >>> a[1] = np.ma.masked >>> b = np.arange(2, 5) >>> a masked_array(data=[0, --, 2], mask=[False, True, False], fill_value=999999) >>> b array([2, 3, 4]) >>> np.concatenate([a, b]) masked_array(data=[0, 1, 2, 2, 3, 4], mask=False, fill_value=999999) >>> np.ma.concatenate([a, b]) masked_array(data=[0, --, 2, 2, 3, 4], mask=[False, True, False, False, False, False], fill_value=999999) 

Источник

numpy.concatenate#

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

axis int, optional

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

out ndarray, optional

If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.

dtype str or dtype

If provided, the destination array will have this dtype. Cannot be provided together with out.

Controls what kind of data casting may occur. Defaults to ‘same_kind’. For a description of the options, please see casting .

Concatenate function that preserves input masks.

Split an array into multiple sub-arrays of equal or near-equal size.

Split array into a list of multiple sub-arrays of equal size.

Split array into multiple sub-arrays horizontally (column wise).

Split array into multiple sub-arrays vertically (row wise).

Split array into multiple sub-arrays along the 3rd axis (depth).

Stack a sequence of arrays along a new axis.

Assemble arrays from blocks.

Stack arrays in sequence horizontally (column wise).

Stack arrays in sequence vertically (row wise).

Stack arrays in sequence depth wise (along third dimension).

Stack 1-D arrays as columns into a 2-D array.

When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are not preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead.

>>> a = np.array([[1, 2], [3, 4]]) >>> b = np.array([[5, 6]]) >>> np.concatenate((a, b), axis=0) array([[1, 2], [3, 4], [5, 6]]) >>> np.concatenate((a, b.T), axis=1) array([[1, 2, 5], [3, 4, 6]]) >>> np.concatenate((a, b), axis=None) array([1, 2, 3, 4, 5, 6]) 

This function will not preserve masking of MaskedArray inputs.

>>> a = np.ma.arange(3) >>> a[1] = np.ma.masked >>> b = np.arange(2, 5) >>> a masked_array(data=[0, --, 2], mask=[False, True, False], fill_value=999999) >>> b array([2, 3, 4]) >>> np.concatenate([a, b]) masked_array(data=[0, 1, 2, 2, 3, 4], mask=False, fill_value=999999) >>> np.ma.concatenate([a, b]) masked_array(data=[0, --, 2, 2, 3, 4], mask=[False, True, False, False, False, False], fill_value=999999) 

Источник

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