0
3

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.

pythonとnumpyで行列を自由に操る!

Posted at

まずは行列を作ります!

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

print(arr)
"""
[[1 2 3]
 [4 5 6]
 [7 8 9]]
"""

ちなみに、tupleでリストの中にリストを作る方法だとデータ型がリストのまんまで行列にならないので注意してください!


arr= ([[1,2,3],
       [4,5,6],
       [7,8,9]])

print(type(arr)
# list

arr.dtype
# AttributeError: 'list' object has no attribute 'dtype'

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

type(arr)
# numpy.ndarray

arr.dtype
# dtype('int64')

スライスを使って、2,3,5,6だけを取り出す!

arr[:2,1:]

"""
array([[2, 3],
       [5, 6]])
"""

検証してみましょう!

arr[:2]

"""
array([[1, 2, 3],
       [4, 5, 6]])
"""

これで、3番目までのリスト(1番目と2番目)を取り出せます!
この方法を使って、後は2番目から([1:]として)取り出せば良いのですね!

ちなみに、


arr[:2][1:]
# array([[4, 5, 6]])

このように指定すると、最初の[:2]で3番目までのリスト(1番目と2番目)を取り出して、[1:]で2つのリストから2番目のリストを取り出すようになってしまうのでご注意ください!

おわりに

まだまだ使いきれてないですが、便利なやり方を見つけたら随時更新してまいります!
イケてる方法等あれば、教えていただけますと幸いです!

0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?