PythonにおけるNumPyの概要と使用例

9490 ワード

NumPyはPython言語の拡張パッケージです.多次元配列とマトリクス演算をサポートし、配列演算に大量の数学関数ライブラリを提供します.NumPyはMatlabに似た機能と操作方法を提供しています.両方が直訳言語であるためです.
NumPyは通常、SciPy(Scientific Python)とMatplotlib(グラフィックスライブラリ)とともに使用され、この組み合わせはMatlabの代わりに広く使用され、流行の技術プラットフォームである.
NumPyで定義される最も重要なオブジェクトは、ndarrayと呼ばれるN次元配列タイプです.同じタイプの要素の集合を記述し、ゼロベースのインデックスを使用して集合内の要素にアクセスできます.基本的なndarrayは、NumPyの配列関数を使用して作成されます:numpy.array.
NumPyはPythonよりも多くの種類の数値タイプをサポートしています.NumPy値は、dtype(データ型)オブジェクトのインスタンスであり、各オブジェクトに固有の特徴があります.
次のndarrayの説明はhttps://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html(このリンクでは、ndarrayに含まれるさまざまな関数の説明を参照してください):
         An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size. The number of dimensions and items in an array is defined by its shape, which is a tuple of N positive integers that specify the sizes of each dimension. The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray.
As with other container objects in Python, the contents of an ndarray can be accessed and modified by indexing or slicing the array, and via the methods and attributes of the ndarray.
Different ndarrays can share the same data, so that changes made in one ndarray may be visible in another. That is, an ndarray can be a “view” to another ndarray, and the data it is referring to is taken care of by the “base” ndarray. ndarrays can also be views to memory owned by Python strings or objects implementing the buffer or array interfaces.
以下に、NumPyの簡単な使用例を示します(参考:https://wizardforcel.gitbooks.io/ts-numpy-tut/content/):
import numpy as np
from matplotlib import pyplot as plt

#   
a = np.array([1, 2, 3]); print(a) # [1 2 3]
#         
b = np.arange(10); print(b) # [0 1 2 3 4 5 6 7 8 9]

#   
c = np.array([[1, 2], [3, 4]]); print(c) # [[1 2]
										 #  [3 4]]
# ndmin           
d = np.array([1, 2, 3, 4, 5]); print(d) 		 # [1 2 3 4 5]
e = np.array([1, 2, 3, 4, 5], ndmin=2); print(e) # [[1 2 3 4 5]]

# dtype:         
f = np.array([1, 2, 3], dtype=complex); print(f) # [1.+0.j 2.+0.j 3.+0.j]

#         
dt = np.dtype(np.int32); print(dt) # int32
# int8,int16,int32,int64          'i1', 'i2', 'i4', 'i8'
dt = np.dtype('i8'); print(dt) # int64

#     shape
a = np.array([[1, 2, 3], [4, 5, 6]]); print(a); # [[1 2 3]
												#  [4 5 6]]
a.shape = (3, 2); print(a)                      # [[1 2]
												#  [3 4]
												#  [5 6]]
a = np.array([[1, 2, 3], [4, 5, 6]]); b = a.reshape(3, 2); print(b) # [[1 2]
												                    #  [3 4]
												                    #  [5 6]]

# ndim:       
a = np.arange(24); print(a.ndim) # 1
# numpy.reshape:               
b = a.reshape(2, 4, 3); print(b.ndim) # 3

# itemsize:                
a = np.array([1, 2, 3, 4], dtype=np.int8); print(a.itemsize) # 1
a = np.array([1, 2, 3, 4], dtype=np.float32); print(a.itemsize) # 4

#    
x = np.empty([3, 2], dtype='i1'); print(x) #   x       ,        

#   5 0   ,      ,    float
x = np.zeros(5, dtype=np.int); print(x) # [0 0 0 0 0]
#   6 1     ,      ,    float
x = np.ones([2, 3], dtype=int); print(x) # [[1 1 1]
										 #  [1 1 1]]

#       ndarray
x = [1, 2, 3]
a = np.asarray(x, dtype=float); print(a) # [1. 2. 3.]
#       ndarray
x = (1, 2, 3)
a = np.asarray(x, dtype=complex); print(a) # [1.+0.j 2.+0.j 3.+0.j]

#      range()        
x = range(5); print(x) # range(0, 5)
#          
it = iter(x); print(it) # 
#        ndarray, fromiter              ndarray  ,          
y = np.fromiter(it, dtype=float); print(y) # [0. 1. 2. 3. 4.]

# arange    ndarray  ,            
# numpy.arange(start, stop, step, dtype), start   ,   0;stop   ,   ; step  ,   1
x = np.arange(4, dtype=float); print(x) # [0. 1. 2. 3.]
x = np.arange(10, 20, 2); print(x) # [10  12  14  16  18]

# numpy.linspace,      arange,     ,              ,     
# numpy.linspace(start, stop, num, endpoint, retstep, dtype)
# start,   ;stop,   ,  endpoint true,        ;num,           ,   50;
# endpoint,       stop ,   true;retstep,   true,    ,           
x = np.linspace(10, 20, 5); print(x) # [10. 12.5 15. 17.5  20.]
x = np.linspace(10, 20, 5, endpoint=False); print(x) # [10. 12. 14. 16. 18.]
x = np.linspace(1,2,5, retstep=True); print(x) # (array([ 1.  ,  1.25,  1.5 ,  1.75,  2.  ]), 0.25)

# numpy.logspace,     ndarray  ,               .                 ,   10
# numpy.logscale(start, stop, num, endpoint, base, dtype)
# base,       ,   10;     numpy.linspace
a = np.logspace(1.0, 2.0, num=5); print(a) # [10. 17.7827941 31.6227766 56.23413252 100.]
a = np.logspace(1, 10, num=5, base=2); print(a) # [2. 9.51365692 45.254834 215.2694823 1024.]

# ndarray                    ,  Python         ;
#     :   start、stop step        slice       Python slice  ,          
a = np.arange(10); s = slice(2,7,2); print(a[s]) # [2 4 6]
#              (start:stop:step)     ndarray  ,          
a = np.arange(10); b = a[2:7:2]; print(b) # [2 4 6]
a = np.arange(10); b = a[2:]; print(b) # [2 3 4 5 6 7 8 9]
a = np.arange(10); b = a[2:5]; print(b) # [2 3 4]
#           (...),                 
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
b = a[..., 1]; print(b) # [2 4 5]
c = a[1, ...]; print(c) # [3 4 5]

#     :    ndarray      ,            ndarray,         
#        ,          ndarray,             
#     :  :  N             
x = np.array([[1, 2], [3, 4], [5, 6]])
# y     x (0,0), (1,1), (2,0)      
y = x[[0,1,2], [0,1,0]]; print(y) # [1 4 5]

#     :   :              ,           
x = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
y = x[x > 5]; print(y) # [6 7 8 9 10 11]

# ~(     )   NaN
x = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
y = x[~np.isnan(x)]; print(y) # [1. 2. 3. 4. 5.]

#             
x = np.array([1, 2+6j, 5, 3.5+5j])  
y = x[np.iscomplex(x)]; print(y) # [2.0+6.j 3.5+5.j]

#   :  NumPy                   ,                    
#             ,              。  , NumPy                  ,         。
#                 ,           
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
c = a * b; print(c) # [10 40 90 160]

a = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0]])
b = np.array([1.0,2.0,3.0])
c = a + b; print(c) # [[1.0 2.0 3.0]
                    #  [11. 12. 13.]]

#       :NumPy          numpy.nditer。              ,            。
#           Python   Iterator     
a = np.arange(0, 60, 5)
a = a.reshape(3,4)
for x in np.nditer(a):
	print(x, end=' ') # 0 5 10 15 20 25 30 35 40 45 50 55

print('
') # : nditer op_flags, , . for x in np.nditer(a, op_flags=['readwrite']): x[...]=2*x; print(x, end=' ') # 0 10 20 30 40 50 60 70 80 90 100 110 print('
') # numpy.raval: , 。 a = np.arange(8).reshape(2,4) b = a.ravel(); print(b) # [0 1 2 3 4 5 6 7] # numpy.unique: a = np.array([5, 2, 6, 2, 7, 5, 6, 8, 2, 9]) u = np.unique(a); print(u) # [2 5 6 7 8 9] # :bitwise_and, bitwise_or, invert, left_shift, right_shift a,b = 13,17; print(bin(a), bin(b)) # 0b1101 0b10001 c = np.bitwise_and(13, 17); print(c) # 1 c = np.bitwise_or(13, 17); print(c) # 29 # :add, multiply, center, capitalize, title, lower, upper, split, splitlines, strip, join, replace, decode, encode print(np.char.add(['hello'],[' Spring'])) # ['hell Spring'] print(np.char.multiply('Hello ',3)) # Hello Hello Hello # numpy.char.center: , , fillchar print(np.char.center('hello', 20, fillchar = '*')) # *******hello******** a = np.char.encode('hello', 'cp500'); print(a) # b'\x88\x85\x93\x93\x96' b = np.char.decode(a, 'cp500'); print(b) # hello # :sin, cos, tan, arcsin, arccos, arctan a = np.array([0, 30, 45, 60, 90]) b = np.sin(a*np.pi/180); print(b) # [ 0. 0.5 0.70710678 0.8660254 1.] # : around, floor, ceil a = np.array([1.0, 5.55, 123, 0.567, 25.532]) b = np.around(a); print(b) # [1. 6. 123. 1. 26.] # :add, subtract, multiply, divide, reciprocal, power, mod a, b = [5, 6], [7, 10] c = np.subtract(a, b); print(c) # [-2 -4] # : , , , amin, amax, ptp, percentile, median, mean, average, std a = np.array([1, 2, 3, 4, 5]) print(np.amin(a)) # 1 print(np.median(a)) # 3.0 print(np.mean(a)) # 3.0 # : , , 。 , 。 # , , a = np.arange(6); print(a) # [0 1 2 3 4 5] print(id(a)) # 54667664 b = a print(id(b)) # 54667664 b.shape = 2,3 print(a); # [[0 1 2] # [3 4 5]] # IO: ndarray # load() save() NumPy ( npy ) # loadtxt() savetxt() a = np.array([1, 2, 3, 4, 5]) np.save('E:/GitCode/Python_Test/test_data/outfile.npy', a) b = np.load('E:/GitCode/Python_Test/test_data/outfile.npy') print(b) # [1 2 3 4 5] np.savetxt('E:/GitCode/Python_Test/test_data/outfile.txt', a) b = np.loadtxt('E:/GitCode/Python_Test/test_data/outfile.txt') print(b) # [1. 2. 3. 4. 5.] # Matplotlib Python , http://matplotlib.org/examples/ matplotlib x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y, 'ob') plt.show()

GitHub:  https://github.com/fengbingchun/Python_Test