Concat two arrays python

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) 

Источник

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

Источник

6 Ways to Concatenate Lists in Python

6 Ways to Concatenate Lists in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

  • concatenation (+) operator
  • Naive Method
  • List Comprehension
  • extend() method
  • ‘*’ operator
  • itertools.chain() method

1. Concatenation operator (+) for List Concatenation

The ‘+’ operator can be used to concatenate two lists. It appends one list at the end of the other list and results in a new list as output.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = list1 + list2 print ("Concatenated list:\n" + str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

2. Naive Method for List Concatenation

In the Naive method, a for loop is used to traverse the second list. After this, the elements from the second list get appended to the first list. The first list results out to be the concatenation of the first and the second list.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] print("List1 before Concatenation:\n" + str(list1)) for x in list2 : list1.append(x) print ("Concatenated list i.e. list1 after concatenation:\n" + str(list1)) 
List1 before Concatenation: [10, 11, 12, 13, 14] Concatenated list i.e. list1 after concatenation: [10, 11, 12, 13, 14, 20, 30, 42] 

3. List Comprehension to concatenate lists

Python List Comprehension is an alternative method to concatenate two lists in Python. List Comprehension is basically the process of building/generating a list of elements based on an existing list.

It uses for loop to process and traverses the list in an element-wise fashion. The below inline for-loop is equivalent to a nested for loop.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = [j for i in [list1, list2] for j in i] print ("Concatenated list:\n"+ str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

4.Python extend() method for List Concatenation

Python’s extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] print("list1 before concatenation:\n" + str(list1)) list1.extend(list2) print ("Concatenated list i.e ,ist1 after concatenation:\n"+ str(list1)) 

All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

list1 before concatenation: [10, 11, 12, 13, 14] Concatenated list i.e ,ist1 after concatenation: [10, 11, 12, 13, 14, 20, 30, 42] 

5. Python ‘*’ operator for List Concatenation

Python’s ‘*’ operator can be used to easily concatenate two lists in Python.

The ‘*’ operator in Python basically unpacks the collection of items at the index arguments.

For example: Consider a list my_list = [1, 2, 3, 4].

The statement *my_list would replace the list with its elements at the index positions. Thus, it unpacks the items of the lists.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = [*list1, *list2] print ("Concatenated list:\n " + str(res)) 

In the above snippet of code, the statement res = [*list1, *list2] replaces the list1 and list2 with the items in the given order i.e. elements of list1 after elements of list2. This performs concatenation and results in the below output.

Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

6. Python itertools.chain() method to concatenate lists

Python itertools modules’ itertools.chain() function can also be used to concatenate lists in Python.

The itertools.chain() function accepts different iterables such as lists, string, tuples, etc as parameters and gives a sequence of them as output.

It results out to be a linear sequence. The data type of the elements doesn’t affect the functioning of the chain() method.

For example: The statement itertools.chain([1, 2], [‘John’, ‘Bunny’]) would produce the following output: 1 2 John Bunny

import itertools list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = list(itertools.chain(list1, list2)) print ("Concatenated list:\n " + str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

Conclusion

Thus, in this article, we have understood and implemented different ways of Concatenating lists in Python.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Читайте также:  Byte array memory java
Оцените статью