📜  np.hstack - Python (1)

📅  最后修改于: 2023-12-03 15:17:59.094000             🧑  作者: Mango

np.hstack - Python

The np.hstack function in Python is a NumPy function that is used to horizontally stack arrays. It takes a sequence of arrays as input and returns a single array by concatenating them horizontally.

Syntax

The syntax for using np.hstack is as follows:

np.hstack(tup)

where tup is a sequence of arrays.

Parameters

The np.hstack function takes only one parameter which is a sequence of arrays. This parameter is:

  • tup: A sequence of arrays to be horizontally stacked. The arrays must have the same shape along all but the second axis.
Return Value

The np.hstack function returns a single array by stacking the input arrays horizontally.

Example

Let's see an example of how to use np.hstack to horizontally stack arrays:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.array([7, 8, 9])

result = np.hstack((a, b, c))

print(result)

Output:

[1 2 3 4 5 6 7 8 9]

In this example, three arrays a, b, and c are horizontally stacked using np.hstack. The resulting array contains all the elements of the three input arrays in a single row.

Conclusion

The np.hstack function in Python is a useful tool for horizontally stacking arrays. It allows you to combine multiple arrays into a single array by concatenating them horizontally. This function is particularly helpful in data manipulation and preprocessing tasks where you need to combine arrays along the second axis.