# NumPy配列の結合と分割

Date: 2015-07-29 / tags: Python, NumPy
スポンサーリンク

## 結合

`vstack`, `r_``concatenate(axis=0)`と、`hstack`, `c_``concatenate(axis=1)`と同等。

```import numpy as np

arr1 = np.arange(6).reshape(2, 3)
arr2 = np.arange(6, 12).reshape(2, 3)

print arr1
# [[0 1 2]
#  [3 4 5]]

print arr2
# [[ 6  7  8]
#  [ 9 10 11]]

arr_v = np.concatenate((arr1, arr2), axis=0)
arr_v = np.vstack((arr1, arr2))
arr_v = np.r_[arr1, arr2]

print arr_v
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]

arr_h = np.concatenate((arr1, arr2), axis=1)
arr_h = np.hstack((arr1, arr2))
arr_h = np.c_[arr1, arr2]

print arr_h
# [[ 0  1  2  6  7  8]
#  [ 3  4  5  9 10 11]]
```

## 分割

2つ目の引数（`indices_or_sections`）が、

• 整数値N : N等分に分割（割り切れない場合はエラー）
• 配列 : 各値の位置で分割

`vsplit``split(axis=0)`と、`hsplit``split(axis=1)`と同等。

```import numpy as np

arr = np.arange(12).reshape(3, 4)

print arr
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

a, b = np.split(arr, 2, axis=1)
a, b = np.hsplit(arr, 2)

print a
# [[0 1]
#  [4 5]
#  [8 9]]

print b
# [[ 2  3]
#  [ 6  7]
#  [10 11]]

a, b, c = np.split(arr, [1, 3], axis=1)
a, b, c = np.hsplit(arr, [1, 3])

print a
# [[0]
#  [4]
#  [8]]

print b
# [[ 1  2]
#  [ 5  6]
#  [ 9 10]]

print c
# [[ 3]
#  [ 7]
#  [11]]

a, b = np.split(arr, [1], axis=0)
a, b = np.vsplit(arr, [1])

print a
# [[0 1 2 3]]

print b
# [[ 4  5  6  7]
#  [ 8  9 10 11]]
```
スポンサーリンク
シェア