Python:1次元・多次元 numpy配列の作成方法

その買うを、もっとハッピーに。|ハピタス

このサイトを参照しながら、1次元numpy配列と多次元numpy配列の作成方法を学習する。

スポンサーリンク

git clone

cd git
/home/workspace/git
!git clone https://github.com/CHPC-UofU/python-lectures.git
Cloning into 'python-lectures'...
remote: Enumerating objects: 115, done.
remote: Counting objects: 100% (115/115), done.
remote: Compressing objects: 100% (83/83), done.
remote: Total 115 (delta 43), reused 99 (delta 30), pack-reused 0
Receiving objects: 100% (115/115), 3.66 MiB | 3.62 MiB/s, done.
Resolving deltas: 100% (43/43), done.
cd python-lectures/notebooks
/home/workspace/git/python-lectures/notebooks
%run set_env.py
%matplotlib inline
Check versions:
  numpy version     :'1.15.4'
  matplotlib version:'3.0.2'
スポンサーリンク

Creation of arrays

1D array:

There are several options to create a 1D numpy arrays. Among them, the most frequently used are:
1次元numpy配列を作成するためのいくつかの選択肢がある。それらの中で、最も頻繁に使われているのが、

  • numpy.array() : create an numpy array from a python array-like object
    python配列様オブジェクトからnumpy配列を作成する。

  • numpy.arange({start], stop[, step], dtype=None) : return evenly spaced values with given interval
    所与の間隔を持った等間隔の値を返す。

  • numpy.linspace(start, stop, num=50, endpoint=True) : return evenly spaced numbers over a specified interval.
    所定の間隔に渡り等間隔の数字を返す。

# np.array
a=np.array([1,3,5,10])
print("a := np.array(1):\n{0}\n".format(a))

b=np.array(range(2,10,3)) 
print("b := np.array(range(10)):\n{0}".format(b))
a := np.array(2):
[ 1  3  5 10]

b := np.array(range(10)):
[2 5 8]
# np.arange (MORE GENERAL than its Python Counterpart -> Why?)
a=np.arange(10)
print("a := np.arange(10):\n{0}\n".format(a))

b=np.arange(0.,1.0,0.1)  
print("b := np.arange(0.,1.0,0.1):\n{0}".format(b))
a := np.arange(10):
[0 1 2 3 4 5 6 7 8 9]

b := np.arange(0.,1.0,0.1):
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
# [0,1] with equidistant intervals 
#  #Intervals: (b-a)/dx
a=np.linspace(0,1,11)   
print("a := np.linspace(0,1,11):\n{0}\n".format(a))

# [0,1[ with equidistant intervals
b=np.linspace(0,1,10,endpoint=False) 
print("b := np.linspace(0,1,10,endpoint=False):\n{0}".format(b))
a := np.linspace(0,1,11):
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]

b := np.linspace(0,1,10,endpoint=False):
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

Note:

  • The np.logspace function returns numbers spaced evenly on a log scale (default base:10)
    np.logspace関数は、対数尺度(デフォルト基数:10)の等間隔数字を返す。

Multi dimensional arrays:

There several (general) ways to create a N$D$ numpy array.
N$D$ numpy配列を作成するためのいくつかの(一般的な)方法が存在する。
Among them(以下はそれらの一部):

  • numpy.array: create an numpy array from a python array-like object (as in the $1D$ case)
    ($1D$同様)python配列様オブジェクトからnumpy配列を作成する。
  • numpy.reshape(a,newshape[,order]) : gives a new shape (dimensionality) to an array without changing its data
    データを変える事なく配列に新たな形状(次元)を与える

    • newshape: tuple(タプル)
    • order(順序): ‘F’, ‘C’
      • ‘C’: C-order => row-order(行順)(Default)
      • ‘F’: Fortran-order => column-order(列順)
  • numpy.meshgrid : returns coordinate matrices from two or more $1D$ coordinate vectors
    2つ以上の$1D$座標ベクトルから座標マトリックスを返す。

We can convert a N$D$ array into a 1$D$ array as follows:
N$D$配列は以下のように1$D$配列に変換できる。

  • numpy.reshape
  • numpy.flatten(order=’C’) : return a copy of a flattened array
    平坦化配列のコピーを返す。
  • numpy.ravel(a,order=’C’) : return a $1D$ array
    $1D$配列を返す。
# Numpy-array from 2D List
a=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
print("a := np.array([3,[5,6,7,8],[9,10,11,12]]) :\n{0}\n".format(a))

# Reshape
b=np.arange(1,13).reshape(3,4)
print("b := np.arange(1,13).reshape(3,4) :\n{0}".format(b))
a := np.array([4,[5,6,7,8],[9,10,11,12]]) :
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

b := np.arange(1,13).reshape(3,4) :
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
a=np.array([[1,2,3],[4,5,6]])
print("a := np.array([5,[4,5,6]]) :\n{0}\n".format(a))

# Row-order (C)
b1=np.reshape(a,(1,6))
print("b1:= np.reshape(a,(1,6)) :\n{0}\n".format(b1))

# Column-order Fortran
b2=np.reshape(a,(1,6),order='F')
print("b2:= np.reshape(a,(1,6),order='F') :\n{0}".format(b2))
a := np.array([6,[4,5,6]]) :
[7
 [4 5 6]]

b1:= np.reshape(a,(1,6)) :
[1 2 3 4 5 6]

b2:= np.reshape(a,(1,6),order='F') :
[1 4 2 5 3 6]
# Meshgrid -> perfect to make grids for plots
X=np.arange(-8,8, 0.25)
Y=np.arange(-8,8, 0.25)

print(" BEFORE Invoking the Meshgrid function:")
print("   X := dim:{0}:\n{1}\n".format(X.shape,X))
print("   Y := dim:{0}:\n{1}\n".format(Y.shape,Y))

EPS=1.0E-4
X,Y=np.meshgrid(X,Y)
print(" AFTER Invoking the Meshgrid function:")
print("   X := dim:{0}:\n{1}\n".format(X.shape,X))
print("   Y := dim:{0}:\n{1}\n".format(Y.shape,Y))
r = np.sqrt(X**2 + Y**2) + EPS
Z = np.sin(r)/r

# Matplot lib example
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap=plt.cm.get_cmap('RdBu'),
        linewidth=0, antialiased=False)
ax.set_zlim(-0.1, 1.00)
ax.set_title("Mexican Hat Style Plot")

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
 BEFORE Invoking the Meshgrid function:
   X := dim:(64,):
[-8.   -7.75 -7.5  -7.25 -7.   -6.75 -6.5  -6.25 -6.   -5.75 -5.5  -5.25
 -5.   -4.75 -4.5  -4.25 -4.   -3.75 -3.5  -3.25 -3.   -2.75 -2.5  -2.25
 -2.   -1.75 -1.5  -1.25 -1.   -0.75 -0.5  -0.25  0.    0.25  0.5   0.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  4.    4.25  4.5   4.75  5.    5.25  5.5   5.75  6.    6.25  6.5   6.75
  7.    7.25  7.5   7.75]

   Y := dim:(64,):
[-8.   -7.75 -7.5  -7.25 -7.   -6.75 -6.5  -6.25 -6.   -5.75 -5.5  -5.25
 -5.   -4.75 -4.5  -4.25 -4.   -3.75 -3.5  -3.25 -3.   -2.75 -2.5  -2.25
 -2.   -1.75 -1.5  -1.25 -1.   -0.75 -0.5  -0.25  0.    0.25  0.5   0.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  4.    4.25  4.5   4.75  5.    5.25  5.5   5.75  6.    6.25  6.5   6.75
  7.    7.25  7.5   7.75]

 AFTER Invoking the Meshgrid function:
   X := dim:(64, 64):
[[-8.   -7.75 -7.5  ...  7.25  7.5   7.75]
 [-8.   -7.75 -7.5  ...  7.25  7.5   7.75]
 [-8.   -7.75 -7.5  ...  7.25  7.5   7.75]
 ...
 [-8.   -7.75 -7.5  ...  7.25  7.5   7.75]
 [-8.   -7.75 -7.5  ...  7.25  7.5   7.75]
 [-8.   -7.75 -7.5  ...  7.25  7.5   7.75]]

   Y := dim:(64, 64):
[[-8.   -8.   -8.   ... -8.   -8.   -8.  ]
 [-7.75 -7.75 -7.75 ... -7.75 -7.75 -7.75]
 [-7.5  -7.5  -7.5  ... -7.5  -7.5  -7.5 ]
 ...
 [ 7.25  7.25  7.25 ...  7.25  7.25  7.25]
 [ 7.5   7.5   7.5  ...  7.5   7.5   7.5 ]
 [ 7.75  7.75  7.75 ...  7.75  7.75  7.75]]

# Flatten multi-dimensional array
a=np.arange(30).reshape((2,3,5))
print("a := np.arange(30).reshape((2,3,5)) :\n{0}\n".format(a))

b1=a.ravel(order='C')
print("b1 := np.ravel(a,order='C') :\n{0}\n".format(b1))

b2=a.ravel(order='F')
print("b2 := np.ravel(a,order='F') :\n{0}\n".format(b2))

b3=a.flatten(order='F')
print("b3 := np.flatten(a,order='F') :\n{0}".format(b3))
a := np.arange(30).reshape((2,3,5)) :
[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]
  [10 11 12 13 14]]

 [[15 16 17 18 19]
  
  [25 26 27 28 29]]]

b1 := np.ravel(a,order='C') :
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25 26 27 28 29]

b2 := np.ravel(a,order='F') :
[ 0 15  5 20 10 25  1 16  6 21 11 26  2 17  7 22 12 27  3 18  8 23 13 28
  4 19  9 24 14 29]

b3 := np.flatten(a,order='F') :
[ 0 15  5 20 10 25  1 16  6 21 11 26  2 17  7 22 12 27  3 18  8 23 13 28
  4 19  9 24 14 29]
スポンサーリンク

Exercises:

Create a $1D$ numpy array containing the following entries :
[2 4 8 16 32 64 128 256 512 1024] 上の配列を含む$1D$ numpy配列を作成せよ。

import numpy as np
pow = []
for i in range(1,11):
    pow.append(2**i)
print("1D array:\n{0}".format(np.array(pow)))
1D array:
[   2    4    8   16   32   64  128  256  512 1024]

模範解答は以下のようになっている。

ex = [i for i in range(1,11)]
lst = [2**i for i in ex]
print("1D array:\n{0}".format(np.array(lst)))
1D array:
[   2    4    8   16   32   64  128  256  512 1024]

Create a numpy array (using only regular python & the np.array construct) which generates the same numbers/numpy vector as the function call:
(標準pythonとnp.array構成だけを使って)以下の関数呼び出しと同じ数字とnumpyベクトルを生成するnumpy配列を作成せよ。
x = np.logspace(start=2, stop=3, num=5, base=10)

i.e.:
x = [ 100. 177.827941 316.22776602 562.34132519 1000. ]

start = 2.
stop   = 3.
num = 5 
base = 10
dx= (stop - start)/float(num-1)
a = []
for i in range(num):
    a.append(base**(start+i*dx))
print("{0}".format(np.array(a)))
print("{0}".format(np.logspace(start,stop,num,base)))
[ 100.          177.827941    316.22776602  562.34132519 1000.        ]
[ 100.          177.827941    316.22776602  562.34132519 1000.        ]

模範解答

start = 2.
stop   = 3.
num = 5 
base = 10
dx= (stop - start)/float(num-1)

pt = [ start+i*dx for i in range(num)]
lst = [base**item for item in pt]
print("{0}".format(np.array(lst)))
print("{0}".format(np.logspace(start,stop,num,base)))
[ 100.          177.827941    316.22776602  562.34132519 1000.        ]
[ 100.          177.827941    316.22776602  562.34132519 1000.        ]

Create a 2$D$ numpy array ($A$) with shape (5×6) starting at the integer value 30 and ending at 1.
整数値30から1の形状(5×6)を持つ2$D$ numpy配列($A$)を作成せよ。
The result should be like this:
結果は以下のようになるはず。
$\begin{equation*}
A =
\begin{pmatrix}
30 & 29 & 28 & 27 & 26 & 25 \\
24 & 23 & 22 & 21 & 20 & 19 \\
18 & 17 & 16 & 15 & 14 & 13 \\
12 & 11 & 10 & 9 & 8 & 7 \\
6 & 5 & 4 & 3 & 2 & 1
\end{pmatrix}
\end{equation*}
$

a = range(30,0,-1)
print("{0}".format(np.array(a).reshape((5,6))))
[[30 29 28 27 26 25]
 [24 23 22 21 20 19]
 [18 17 16 15 14 13]
 [12 11 10  9  8  7]
 [ 6  5  4  3  2  1]]
スポンサーリンク
スポンサーリンク