Python numpy сложение массивов

numpy.sum#

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.

dtype dtype, optional

The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

out ndarray, optional

Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

keepdims bool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray , however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

initial scalar, optional

Starting value for the sum. See reduce for details.

Elements to include in the sum. See reduce for details.

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

Equivalent functionality of add .

Cumulative sum of array elements.

Integration of array values using the composite trapezoidal rule.

Arithmetic is modular when using integer types, and no error is raised on overflow.

The sum of an empty array is the neutral element 0:

For floating point numbers the numerical precision of sum (and np.add.reduce ) is in general limited by directly adding each number individually to the result causing rounding errors in every step. However, often numpy will use a numerically better approach (partial pairwise summation) leading to improved precision in many use-cases. This improved precision is always provided when no axis is given. When axis is given, it will depend on which axis is summed. Technically, to provide the best speed possible, the improved precision is only used when the summation is along the fast axis in memory. Note that the exact precision may vary depending on other parameters. In contrast to NumPy, Python’s math.fsum function uses a slower but more precise approach to summation. Especially when summing a large number of lower precision floating point numbers, such as float32 , numerical errors can become significant. In such cases it can be advisable to use dtype=”float64” to use a higher precision for the output.

>>> np.sum([0.5, 1.5]) 2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) 1 >>> np.sum([[0, 1], [0, 5]]) 6 >>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5]) >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1) array([1., 5.]) 

If the accumulator is too small, overflow occurs:

>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8) -128 

You can also start the sum with a value other than zero:

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

Источник

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()
Читайте также:  View string to html

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) 

Источник

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