LoginSignup
1
1

More than 3 years have passed since last update.

#Python基礎(#Numpy 1/2)

Last updated at Posted at 2020-05-06

1.Numpy

Numpy : Pythonの拡張モジュールで多次元配列を扱う際に便利

人より記憶メモリが少ない私はいつも、あれ?これどうだっけ?という状態に
陥ってその度に同じ検索ワードで検索をしてしまうのでこの機にメモしておこうと思います。

環境は以前の記事で作った環境を使用しています。 → Windows10でpython開発準備

2.list to Numpy

pythonのリストからNumpy配列に変換する方法

import numpy as np

a = np.array([0, 1, 2, 3, 4, 5])  # PythonのリストからNumPyの配列を作る
print(a) 
実行結果
[0 1 2 3 4 5]
<class 'numpy.ndarray'>

オブジェクトの型を取得・確認:type()関数

print(type(a))
実行結果

<class 'numpy.ndarray'>

3.lit to Numpy 多次元配列

import numpy as np

b = np.array([[0, 1, 2], [3, 4, 5]])  # 2重のリストからNumPyの2次元配列を作る
print(b)
実行結果
[[0 1 2]
 [3 4 5]]

ndarrayの形状:shape

print(b.shape) # shapeで形状をタプルとして取得(行数、列数)
実行結果
(2, 3)

4.配列の演算1

import numpy as np

a = np.array([[0, 1, 2], [3, 4, 5]])  # 2次元配列

print(a)

#[[0 1 2]
# [3 4 5]]
print(a + 10) # 各要素に10を足す

# [[10 11 12]
#  [13 14 15]]
print(a * 10) # 各要素に10をかける

#[[ 0 10 20]
# [30 40 50]]

5.配列の演算2

配列同士の演算

b = np.array([[0, 1, 2], [3, 4, 5]])  # 2次元配列
c = np.array([[2, 0, 1], [5, 3, 4]])  # 2次元配列

print(b)
print("--------------")
print(c)
print("--------------")
print(b + c)
print("--------------")
print(b * c)
実行結果
[[0 1 2]
 [3 4 5]]
--------------
[[2 0 1]
 [5 3 4]]
--------------
[[2 1 3]
 [8 7 9]]
--------------
[[ 0  0  2]
 [15 12 20]]

※厳密には 2次元配列と1次元配列同士の足し算等も出来る等、少し複雑なルールもあるようだが個人的に良く使うものだけメモ

1
1
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
1
1