若干個數組可以沿不同的軸合合并到一起,vstack,hstack的簡單用法,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
>>> a = np.floor( 10 * np.random.random(( 2 , 2 ))) >>> a array([[ 8. , 8. ], [ 0. , 0. ]]) >>> b = np.floor( 10 * np.random.random(( 2 , 2 ))) >>> b array([[ 1. , 8. ], [ 0. , 4. ]]) >>> np.vstack((a,b)) array([[ 8. , 8. ], [ 0. , 0. ], [ 1. , 8. ], [ 0. , 4. ]]) >>> np.hstack((a,b)) array([[ 8. , 8. , 1. , 8. ], [ 0. , 0. , 0. , 4. ]]) |
column_stack函數功能是將一個1D數組轉化成一個2D數組,相當于將1D數組垂直排列。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
>>> np.column_stack((a,b)) # With 2D arrays array([[ 8. , 8. , 1. , 8. ], [ 0. , 0. , 0. , 4. ]]) >>> a = np.array([ 4. , 2. ]) >>> b = np.array([ 2. , 8. ]) >>> a[:,newaxis] # This allows to have a 2D columns vector array([[ 4. ], [ 2. ]]) >>> np.column_stack((a[:,newaxis],b[:,newaxis])) array([[ 4. , 2. ], [ 2. , 8. ]]) >>> np.vstack((a[:,newaxis],b[:,newaxis])) # The behavior of vstack is different array([[ 4. ], [ 2. ], [ 2. ], [ 8. ]]) |
對于多維數組,hstack沿第二軸,vstack沿第一條軸。
總結
以上就是本文關于Python numpy實現數組合并實例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:https://docs.scipy.org/doc/numpy-dev/user/quickstart.html#changing-the-shape-of-an-array