Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
numpy.vstack() in python
Next article icon

numpy.hstack() function stacks arrays in sequence horizontally (column-wise). It joins arrays along their second axis for 2D arrays or flattens and joins them for 1D arrays. This is useful for combining arrays side by side.

Example:

Python
importnumpyasnpa=np.array([1,2,3])b=np.array([4,5,6])res=np.hstack((a,b))print(res)

Output
[1 2 3 4 5 6]

Arraysaandb are horizontally stacked to form one combined 1D array.

Syntax

numpy.hstack(tup, *, dtype=None, casting='same_kind')

Parameters:

Parameter

Type

Description

tup

sequence of array_like

Arrays to stack horizontally (must match in all but the second axis).

dtype

data-type, optional

Desired data type of the result array.

casting

{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional

Controls data casting (default: 'same_kind').

Returns: This function returns horizontally stacked array of the input arrays.

Examples

Example 1: Horizontal stacking of 2D arrays

Python
importnumpyasnpa=np.array([[1,2],[3,4]])b=np.array([[5,6],[7,8]])res=np.hstack((a,b))print(res)

Output
[[1 2 5 6] [3 4 7 8]]

Each row of a and b is concatenated horizontally to form a wider 2D array.

Example 2: Stacking arrays of different shapes (raises an error)

Python
importnumpyasnpa=np.array([[1,2]])b=np.array([[3,4],[5,6]])res=np.hstack((a,b))

Output

ValueError: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 0, the array a...

Arrays must be compatible in shape except along the concatenation axis.

Example 3:Horizontal stacking with negative numbers

Python
importnumpyasnpa=np.array([-1,-2,-3])b=np.array([4,5,6])res=np.hstack((a,b))print(res)

Output
[-1 -2 -3  4  5  6]

Works with negative integers too. The resulting array preserves the sign of the original numbers.


Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp