LoginSignup
0
0

More than 3 years have passed since last update.

#Python基礎(#Numpy 2/2)

Last updated at Posted at 2020-05-06

前回の記事の続きです。 #Python基礎(#Numpy 1/2)
環境は以前の記事で作った環境を使用しています。 → Windows10でAnaconda python環境構築

1.Numpy 形状変換 reshape

1行6列の配列を2行3列に変換

import numpy as np

a = np.array([0,1,2,3,4,5])
b = a.reshape(2,3)
print(b)
実行結果
[[0 1 2]
 [3 4 5]]

reshapeの引数を-1にすることで、どのような形状の配列でも1次元配列に変換することができます。

import numpy as np

c = np.array([[[0, 1, 2],
                   [3, 4, 5]],

                  [[5, 4, 3],
                   [2, 1, 0]]])  # 3重のリストからNumPyの3次元配列を作る

print(c)
print("--------------------------")
d = c.reshape(-1)
print(d)
実行結果
[[[0 1 2]
  [3 4 5]]

 [[5 4 3]
  [2 1 0]]]
--------------------------
[0 1 2 3 4 5 5 4 3 2 1 0]

2.要素へのアクセス

ndarrayの各要素へのアクセスはlistと同様にインデックスを指定します。

1次元配列
import numpy as np

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

print(b[1, 2])  # b[1][2]と同じ
print(b[1][2])
# 5
# 5
  • 引数として配列を受け取り、返り値として配列を返す
import numpy as np

def func_a(x):
    y = x * 2 + 1
    return y

a = np.array([[0, 1, 2],
              [3, 4, 5]])  # 2次元配列
b = func_a(a)  # 引数として配列を渡す

print(b)
実行結果
[[ 1  3  5]
 [ 7  9 11]]

3.sum, average, max, min

import numpy as np

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

print("sum : ",np.sum(a))
print("average : ",np.average(a))
print("max : ",np.max(a))
print("min : ",np.min(a))

実行結果
sum :  15
average :  2.5
max :  5
min :  0

4.axis 方向を指定して演算

import numpy as np

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

print('axis=0 : ',np.sum(b, axis=0))  # 縦方向で合計
print('axis=1 : ',np.sum(b, axis=1))  # 横方向で合計
実行結果
axis=0 :  [3 5 7]
axis=1 :  [ 3 12]
0
0
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
0