How do you concatenate two NumPy arrays?

How do you concatenate two NumPy arrays?

a) By using the concatenate() function
b) By using the + operator
c) By using the append() function
d) By using the stack() function

Answer:

a) By using the concatenate() function

Explanation:

You can concatenate two NumPy arrays using the concatenate() function. This function joins the arrays along a specified axis, resulting in a new array that combines the elements of the input arrays.

import numpy as np

# Creating two 1D arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Concatenating the arrays
result = np.concatenate((arr1, arr2))
print(result)  # Output: [1 2 3 4 5 6]

In this example, the two 1D arrays arr1 and arr2 are concatenated to form a single 1D array containing all the elements from both arrays.

Concatenation is commonly used to merge datasets, combine results from different computations, or prepare data for further processing in machine learning and data analysis tasks.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top