0
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Numpy~スライス~

Posted at

スライスに関するまとめ

import numpy as np
x = np.arange(10)
# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

# 配列のスライスへは以下を指定してアクセスする
# x[start:stop:step]

x[:5]
# array([0, 1, 2, 3, 4])

x[::2]
# 2つおきに表示
# array([0, 2, 4, 6, 8])

x[1::2]
# 1から始まる2つおきの要素
# array([1, 3, 5, 7, 9])

x[::-1]
# 逆順
# array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

x[5::-1]
# インデックス5から逆順
# array([5, 4, 3, 2, 1, 0])

## 2次元配列

y = np.random.randint(1,10,(3,4))
# array([[4, 2, 2, 9],
#        [1, 7, 5, 3],
#        [5, 2, 1, 6]])

y[:2, :3]
# array([[4, 2, 2],
#        [1, 7, 5]])

y[:2, ::2]
# カット + くりぬき
# array([[4, 2],
#        [1, 5]])

y[::-1, ::-1]
# ひっくり返す
# array([[6, 1, 2, 5],
#        [3, 5, 7, 1],
#        [9, 2, 2, 4]])

y[:, 1]
# 1列目を取り出す
# array([2, 7, 2])

y[1, :]
# 1行目を取り出す
# array([1, 7, 5, 3])

x[:, np.newaxis]
# 列ベクトルの作成
# array([[0],
#        [1],
#        [2],
#        [3],
#        [4],
#        [5],
#        [6],
#        [7],
#        [8],
#        [9]])
0
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?