Hướng dẫn merge array python


Joining NumPy Arrays

Joining means putting contents of two or more arrays in a single array.

Nội dung chính

  • Joining NumPy Arrays
  • Joining Arrays Using Stack Functions
  • Stacking Along Rows
  • Stacking Along Columns
  • Stacking Along Height (depth)
  • Test Yourself With Exercises

In SQL we join tables based on a key, whereas in NumPy we join arrays by axes.

We pass a sequence of arrays that we want to join to the concatenate() function, along with the axis. If axis is not explicitly passed, it is taken as 0.

Example

Join two arrays

import numpy as np

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

arr2 = np.array([4, 5, 6])

arr = np.concatenate((arr1, arr2))

print(arr)

Try it Yourself »

Example

Join two 2-D arrays along rows (axis=1):

import numpy as np

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

arr2 = np.array([[5, 6], [7, 8]])

arr = np.concatenate((arr1, arr2), axis=1)

print(arr)

Try it Yourself »


Joining Arrays Using Stack Functions

Stacking is same as concatenation, the only difference is that stacking is done along a new axis.

We can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking.

We pass a sequence of arrays that we want to join to the stack() method along with the axis. If axis is not explicitly passed it is taken as 0.

Example

import numpy as np

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

arr2 = np.array([4, 5, 6])

arr = np.stack((arr1, arr2), axis=1)

print(arr)

Try it Yourself »



Stacking Along Rows

NumPy provides a helper function: hstack() to stack along rows.

Example

import numpy as np

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

arr2 = np.array([4, 5, 6])

arr = np.hstack((arr1, arr2))

print(arr)

Try it Yourself »


Stacking Along Columns

NumPy provides a helper function: vstack()  to stack along columns.

Example

import numpy as np

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

arr2 = np.array([4, 5, 6])

arr = np.vstack((arr1, arr2))

print(arr)

Try it Yourself »


Stacking Along Height (depth)

NumPy provides a helper function: dstack() to stack along height, which is the same as depth.

Example

import numpy as np

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

arr2 = np.array([4, 5, 6])

arr = np.dstack((arr1, arr2))

print(arr)

Try it Yourself »


Test Yourself With Exercises

Exercise:

Use a correct NumPy method to join two arrays into a single array.

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

arr2 = np.array([4, 5, 6])

arr = np.((arr1, arr2))

Start the Exercise


Hàm concatenate () là một hàm từ gói NumPy. Về cơ bản, hàm này kết hợp các mảng NumPy với nhau. Hàm này về cơ bản được sử dụng để nối hai hoặc nhiều mảng có cùng hình dạng dọc theo một trục được chỉ định. Có những điều cần thiết sau đây cần ghi nhớ:

NumPy’s concatenate () không giống như một phép nối cơ sở dữ liệu truyền thống. Nó giống như việc xếp chồng các mảng NumPy.

Các bài viết liên quan:

Chức năng này có thể hoạt động theo cả chiều dọc và chiều ngang. Điều này có nghĩa là chúng ta có thể nối các mảng với nhau theo chiều ngang hoặc chiều dọc.

Hàm concatenate () thường được viết dưới dạng np.concatenate (), nhưng chúng ta cũng có thể viết nó dưới dạng numpy.concatenate (). Nó phụ thuộc vào cách nhập gói numpy, nhập numpy dưới dạng np hoặc nhập numpy, tương ứng.

Cú pháp

numpy.concatenate ((a1, a2, ...), axis)

Parameter

  1. (a1, a2, …)

Tham số này xác định trình tự của mảng. Ở đây, a1, a2, a3 … là các mảng có hình dạng giống nhau, ngoại trừ chiều tương ứng với trục.

  1. axis: int (tùy chọn)

Tham số này xác định trục mà mảng sẽ được nối với nhau. Theo mặc định, giá trị của nó là 0.

Nó sẽ trả về một ndarray chứa các phần tử của cả hai mảng.

Xem thêm Duyệt mảng trong NumPy

Ví dụ 1: numpy.concatenate ()

import numpy as np  
x=np.array([[1,2],[3,4]])  
y=np.array([[12,30]])  
z=np.concatenate((x,y))  
z  

Trong đoạn code trên

  • Chúng tôi đã tạo một mảng ‘x’ bằng cách sử dụng hàm np.array ().
  • Sau đó, chúng ta đã tạo một mảng khác ‘y’ bằng cách sử dụng cùng một hàm np.array ().
  • Chúng tôi đã khai báo biến ‘z’ và gán giá trị trả về của hàm np.concatenate ().
  • Chúng ta đã chuyển mảng ‘x’ và ‘y’ trong hàm.
  • Cuối cùng, chúng tôi đã in giá trị của ‘z’.

Trong đầu ra, giá trị của cả hai mảng, tức là ‘x’ và ‘y’ được hiển thị theo trục = 0.

Đầu ra:

Ví dụ 2: numpy.concatenate () với axis = 0

import numpy as np  
x=np.array([[1,2],[3,4]])  
y=np.array([[12,30]])  
z=np.concatenate((x,y), axis=0)  
z  

Output:

Ví dụ 3: numpy.concatenate () với axis = 1

import numpy as np  
x=np.array([[1,2],[3,4]])  
y=np.array([[12,30]])  
z=np.concatenate((x,y.T), axis=1)  
z  

Output:

Trong ví dụ trên, ‘.T’ được sử dụng để thay đổi các hàng thành cột và cột thành hàng.

Xem thêm Sử dụng Linear Algebra trong Numpy

Ví dụ 4: numpy.concatenate () với axis = None

import numpy as np  
x=np.array([[1,2],[3,4]])  
y=np.array([[12,30]])  
z=np.concatenate((x,y), axis=None)  
z 

Output:

Trong các ví dụ trên, chúng ta đã sử dụng hàm np.concatenate (). Chức năng này không được bảo toàn che các đầu vào MaskedArray. Có một cách sau đây mà qua đó chúng ta có thể nối các mảng có thể duy trì việc che các đầu vào MaskedArray.

Ví dụ 5: np.ma.concatenate ()

import numpy as np  
x=np.ma.arange(3)  
y=np.arange(3,6)  
x[1]=np.ma.masked  
x  
y  
z1=np.concatenate([x,y])  
z2=np.ma.concatenate([x,y])  
z1  
z2  

Trong đoạn code trên

  • Chúng tôi đã tạo một mảng ‘x’ bằng cách sử dụng hàm np.ma.arrange ().
  • Sau đó, chúng ta đã tạo một mảng ‘y’ khác bằng cách sử dụng cùng một hàm np.ma.arrange ().
  • Chúng tôi đã khai báo biến ‘z1’ và gán giá trị trả về của hàm np.concatenate ().
  • Chúng tôi đã khai báo biến ‘z2’ và gán giá trị trả về của hàm np.ma.concatenate ().
  • Cuối cùng, chúng tôi đã cố gắng in giá trị của ‘z1’ và ‘z2’.

Xem thêm Function trong R, các hàm trong R

This an example code, I want to add the elements of the two arrays. I have imported NumPy and do not want to import array.

from numpy import *

a = array([])
b = array([])
c = array([])

d = input("Enter the length of the arrays")
print ("Enter the elements of array 1")
for i in range(d):
    append(a, int(input("Enter the element ")))
print ("Enter the elements of array 2")
for i in range(d):
    append(b, int(input("Enter the element ")))

for i in range(1, d+1):
    append(c, (a[i] + b[i]))

print(a)
print(b)
print(c)

Expected output should be sum of the elements of the array, but instead I get the following error:

IndexError: index 1 is out of bounds for axis 0 with size 0

dmigo

2,6833 gold badges38 silver badges59 bronze badges

asked Oct 13, 2019 at 19:42

2

First of all you need to convert d to int :

d = int(input("Enter the length of the arrays"))

After that you should assign the result of append function to the array :

print ("Enter the elements of array 1")
for i in range(d):
    a = append(a, int(input("Enter the element ")))
print ("Enter the elements of array 2")
for i in range(d):
    b = append(b, int(input("Enter the element ")))

then the result would be alright

answered Oct 13, 2019 at 20:08

Mohsen_FatemiMohsen_Fatemi

2,1932 gold badges15 silver badges24 bronze badges

0

Function append doesn't mutate the state of its parameters. Instead it returns array with element added.

So to add an element to array you need to: a = append(a, 2)

Also in NumPy you can use add(a,b) to sum two arrays.

If we apply all that to your example we get:

from numpy import *

a = array([])
b = array([])
c = array([])

d = input("Enter the length of the arrays")
print ("Enter the elements of array 1")
for i in range(d):
    a = append(a, int(input("Enter the element ")))
print ("Enter the elements of array 2")
for i in range(d):
    b = append(b, int(input("Enter the element ")))

c = add(a, b)

print(a)
print(b)
print(c)

answered Oct 13, 2019 at 19:56

dmigodmigo

2,6833 gold badges38 silver badges59 bronze badges

2