반응형
#!/usr/bin/env python
# coding: utf-8
# # Numpy tutorial
# ## 참고 사이트
# [Python Tutorial](https://docs.python.org/3/tutorial/)
# [Numpy Tutorial](https://docs.scipy.org/doc/numpy/user/quickstart.html)
# [Numpy Reference](https://docs.scipy.org/doc/numpy/reference/index.html#reference)
# [Numpy 참고사이트](http://taewan.kim/post/numpy_cheat_sheet/#2-배열-생성)
# ---
# ## 1. The Basics
# ### 1.1 An example
# In[ ]:
import numpy as np
# In[ ]:
a = np.arange(15).reshape(3, 5)
a
# In[ ]:
a.shape
# In[ ]:
a.ndim
# In[ ]:
a.dtype.name
# In[ ]:
a.itemsize # size(byte) of item
# In[ ]:
a.size
# In[ ]:
type(a)
# In[ ]:
b = np.array([6, 7, 8])
b
# In[ ]:
type(b)
# ### 1.2 Array Creation
# In[ ]:
a = np.array([2,3,4])
a
# In[ ]:
a.dtype
# In[ ]:
b = np.array([1.2, 3.5, 5.1])
b.dtype
# In[ ]:
a = np.array(1,2,3,4) # WRONG
# In[ ]:
a = np.array([1,2,3,4]) # RIGHT
# In[ ]:
b = np.array([(1.5,2,3), (4,5,6)])
b
# In[ ]:
c = np.array( [ [1,2], [3,4] ], dtype=complex )
c
# In[ ]:
np.zeros( (3,4) )
# In[ ]:
np.ones( (2,3,4), dtype=np.int16 )
# In[ ]:
np.empty( (2,3) )
# In[ ]:
np.arange( 10, 30, 5 )
# In[ ]:
np.arange( 0, 2, 0.3 ) # it accepts float arguments
# In[ ]:
from numpy import pi
np.linspace( 0, 2, 9 ) # 9 numbers from 0 to 2
# In[ ]:
x = np.linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points
f = np.sin(x)
f
# ### 1.3 Printing Arrays
# In[ ]:
a = np.arange(6) # 1d array
print(a)
# In[ ]:
b = np.arange(12).reshape(4,3) # 2d array
print(b)
# In[ ]:
c = np.arange(24).reshape(2,3,4) # 3d array
print(c)
# In[ ]:
print(np.arange(10000))
# In[ ]:
print(np.arange(10000).reshape(100,100))
# ### 1.4 Basic Operations
# In[ ]:
a = np.array( [20,30,40,50] )
a
# In[ ]:
b = np.arange( 4 )
b
# In[ ]:
c = a-b
c
# In[ ]:
b**2
# In[ ]:
10 * np.sin(a)
# In[ ]:
a < 35
# In[ ]:
A = np.array( [[1,1],
[0,1]] )
B = np.array( [[2,0],
[3,4]] )
# In[ ]:
A * B # elementwise product
# In[ ]:
A @ B # matrix product
# In[ ]:
A.dot(B) # another matrix product
# In[ ]:
a = np.ones((2,3), dtype=int)
b = np.random.random((2,3))
# In[ ]:
a *= 3
a
# In[ ]:
b += a
b
# In[ ]:
a += b # b is not automatically converted to integer type
# In[ ]:
a = np.ones(3, dtype=np.int32)
b = np.linspace(0,pi,3)
b.dtype.name
# In[ ]:
c = a+b
c
# In[ ]:
c.dtype.name
# In[ ]:
d = np.exp(c*1j)
d
# In[ ]:
d.dtype.name
# In[ ]:
a = np.random.random((2,3))
a
# In[ ]:
a.sum()
# In[ ]:
a.min()
# In[ ]:
a.max()
# In[ ]:
b = np.arange(12).reshape(3,4)
b
# In[ ]:
b.sum(axis=0) # sum of each column
# In[ ]:
b.min(axis=1) # min of each row
# In[ ]:
b.cumsum(axis=1) # cumulative sum along each row
# ### 1.5 Universal Functions
# In[ ]:
B = np.arange(3)
B
# In[ ]:
np.exp(B)
# In[ ]:
np.sqrt(B)
# In[ ]:
C = np.array([2., -1., 4.])
# In[ ]:
np.add(B, C)
# ### 1.6 Indexing, Slicing and Iterating
# In[ ]:
a = np.arange(10)**3
a
# In[ ]:
a[2]
# In[ ]:
a[2:5]
# In[ ]:
a[:6:2] = -1000
a
# In[ ]:
a[ : :-1] # reversed a
# In[ ]:
for i in a:
print(i**(1/3.))
# In[ ]:
def f(x,y):
return 10*x+y
# In[ ]:
b = np.fromfunction(f,(5,4),dtype=int)
b
# In[ ]:
b[2,3]
# In[ ]:
b[0:5, 1] # each row in the second column of b
# In[ ]:
b[ : ,1] # equivalent to the previous example
# In[ ]:
b[1:3, : ] # each column in the second and third row of b
# In[ ]:
b[-1] # the last row. Equivalent to b[-1,:]
# In[ ]:
c = np.array( [[[ 0, 1, 2], # a 3D array (two stacked 2D arrays)
[ 10, 12, 13]],
[[100,101,102],
[110,112,113]]])
c.shape
# In[ ]:
c[1,...] # same as c[1,:,:] or c[1]
# In[ ]:
c[...,2] # same as c[:,:,2]
# In[ ]:
for row in b:
print(row)
# In[ ]:
for element in b.flat:
print(element)
# ---
# ## 2. Shape Manipulation
# ### 2.1 Changing the shape of an array
# In[ ]:
a = np.floor(10*np.random.random((3,4)))
a
# In[ ]:
a.shape
# In[ ]:
a.ravel() # returns the array, flattened
# In[ ]:
a.reshape(6,2) # returns the array with a modified shape
# In[ ]:
a.T # returns the array, transposed
# In[ ]:
a.T.shape
# In[ ]:
a.shape
# In[ ]:
# The reshape function returns its argument with a modified shape,
# whereas the ndarray.resize method modifies the array itself
a
# In[ ]:
a.resize((2,6))
a
# In[ ]:
a.reshape(3,-1)
# ### 2.2 Stacking together different arrays
# In[ ]:
a = np.floor(10*np.random.random((2,2)))
a
# In[ ]:
b = np.floor(10*np.random.random((2,2)))
b
# In[ ]:
np.vstack((a,b))
# In[ ]:
np.hstack((a,b))
# In[ ]:
from numpy import newaxis
np.column_stack((a,b)) # with 2D arrays
# In[ ]:
a = np.array([4.,2.])
a
# In[ ]:
b = np.array([3.,8.])
b
# In[ ]:
np.column_stack((a,b)) # returns a 2D array
# In[ ]:
np.hstack((a,b)) # the result is different
# In[ ]:
a[:,newaxis] # this allows to have a 2D columns vector
# In[ ]:
np.column_stack((a[:,newaxis],b[:,newaxis]))
# In[ ]:
np.hstack((a[:,newaxis],b[:,newaxis])) # the result is the same
# In[ ]:
# In complex cases, r_ and c_ are useful for creating arrays by stacking numbers along one axis.
# They allow the use of range literals (“:”)
np.r_[1:4,0,4]
# ### 2.3 Splitting one array into several smaller ones
# In[ ]:
a = np.floor(10*np.random.random((2,12)))
a
# In[ ]:
np.hsplit(a,3) # Split a into 3
# In[ ]:
np.hsplit(a,(3,4)) # Split a after the third and the fourth column
# ---
# ## 3. Copies and Views
# ### 3.1 No Copy at All
# In[ ]:
a = np.arange(12)
a
# In[ ]:
b = a # no new object is created
# In[ ]:
b is a # a and b are two names for the same ndarray object
# In[ ]:
b.shape = 3,4 # changes the shape of a
# In[ ]:
a.shape
# In[ ]:
def f(x):
print(id(x))
# In[ ]:
id(a) # id is a unique identifier of an object
# In[ ]:
f(a)
# ### 3.2 View or Shallow Copy
# In[ ]:
c = a.view()
# In[ ]:
c is a
# In[ ]:
c.base is a # c is a view of the data owned by a
# In[ ]:
c.flags.owndata
# In[ ]:
c.shape = 2,6 # a's shape doesn't change
# In[ ]:
a.shape
# In[ ]:
c[0,4] = 1234 # a's data changes
# In[ ]:
a
# In[ ]:
s = a[ : , 1:3] # spaces added for clarity; could also be written "s = a[:,1:3]"
# In[ ]:
s[:] = 10 # s[:] is a view of s. Note the difference between s=10 and s[:]=10
# In[ ]:
a
# ### 3.3 Deep Copy
# In[ ]:
d = a.copy() # a new array object with new data is created
# In[ ]:
d is a
# In[ ]:
d.base is a # d doesn't share anything with a
# In[ ]:
d[0,0] = 9999
# In[ ]:
a
# ---
# ## 4. Fancy indexing and index tricks
# ### 4.1 Indexing with Arrays of Indices
# In[ ]:
a = np.arange(12)**2 # the first 12 square numbers
a
# In[ ]:
i = np.array( [ 1,1,3,8,5 ] ) # an array of indices
i
# In[ ]:
a[i] # the elements of a at the positions i
# In[ ]:
j = np.array( [ [ 3, 4], [ 9, 7 ] ] ) # a bidimensional array of indices
j
# In[ ]:
a[j]
# In[ ]:
palette = np.array( [ [0,0,0], # black
[255,0,0], # red
[0,255,0], # green
[0,0,255], # blue
[255,255,255] ] ) # white
# In[ ]:
image = np.array( [ [ 0, 1, 2, 0 ], # each value corresponds to a color in the palette
[ 0, 3, 4, 0 ] ] )
# In[ ]:
palette[image] # the (2,4,3) color image
# In[ ]:
a = np.arange(12).reshape(3,4)
a
# In[ ]:
i = np.array( [ [0,1], # indices for the first dim of a
[1,2] ] )
j = np.array( [ [2,1], # indices for the second dim
[3,3] ] )
# In[ ]:
a[i,j] # i and j must have equal shape
# In[ ]:
a[i,2]
# In[ ]:
a[:,j] # i.e., a[ : , j]
# In[ ]:
l = [i,j]
l
# In[ ]:
a[l] # equivalent to a[i,j]
# In[ ]:
s = np.array( [i,j] )
s
# In[ ]:
a[s] # not what we want
# In[ ]:
a[tuple(s)] # same as a[i,j]
# In[ ]:
time = np.linspace(20, 145, 5) # time scale
time
# In[ ]:
data = np.sin(np.arange(20)).reshape(5,4) # 4 time-dependent series
data
# In[ ]:
ind = data.argmax(axis=0) # index of the maxima for each series
ind
# In[ ]:
time_max = time[ind] # times corresponding to the maxima
time_max
# In[ ]:
data_max = data[ind, range(data.shape[1])] # => data[ind[0],0], data[ind[1],1]...
data_max
# In[ ]:
np.all(data_max == data.max(axis=0))
# In[ ]:
a = np.arange(5)
a
# In[ ]:
a[[1,3,4]] = 0
a
# In[ ]:
a = np.arange(5)
a
# In[ ]:
a[[0,0,2]]=[1,2,3]
a
# In[ ]:
a = np.arange(5)
a
# In[ ]:
a[[0,0,2]]+=1
a
# ### 4.2 Indexing with Boolean Arrays
# In[ ]:
a = np.arange(12).reshape(3,4)
a
# In[ ]:
b = a > 4
b # b is a boolean with a's shape
# In[ ]:
a[b] # 1d array with the selected elements
# In[ ]:
a[b] = 0 # All elements of 'a' higher than 4 become 0
a
# [망델브로 집합](https://ko.wikipedia.org/wiki/망델브로_집합)
# In[ ]:
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
def mandelbrot( h,w, maxit=20 ):
"""Returns an image of the Mandelbrot fractal of size (h,w)."""
y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ]
c = x+y*1j
z = c
divtime = maxit + np.zeros(z.shape, dtype=int)
for i in range(maxit):
z = z**2 + c
diverge = z*np.conj(z) > 2**2 # who is diverging
div_now = diverge & (divtime==maxit) # who is diverging now
divtime[div_now] = i # note when
z[diverge] = 2 # avoid diverging too much
return divtime
plt.imshow(mandelbrot(400,400))
plt.show()
# In[ ]:
a = np.arange(12).reshape(3,4)
a
# In[ ]:
b1 = np.array([False,True,True]) # first dim selection
b2 = np.array([True,False,True,False]) # second dim selection
# In[ ]:
a[b1,:] # selecting rows
# In[ ]:
a[b1] # same thing
# In[ ]:
a[:,b2] # selecting columns
# In[ ]:
a[b1,b2] # a weird thing to do
# ### 4.3 The ix_() function
# In[ ]:
a = np.array([2,3,4,5])
b = np.array([8,5,4])
c = np.array([5,4,6,8,3])
# In[ ]:
ax,bx,cx = np.ix_(a,b,c)
# In[ ]:
ax
# In[ ]:
bx
# In[ ]:
cx
# In[ ]:
ax.shape, bx.shape, cx.shape
# In[ ]:
result = ax+bx*cx
result
# In[ ]:
result[3,2,4]
# In[ ]:
a[3]+b[2]*c[4]
# In[ ]:
def ufunc_reduce(ufct, *vectors):
vs = np.ix_(*vectors)
r = ufct.identity
for v in vs:
r = ufct(r,v)
return r
# In[ ]:
ufunc_reduce(np.add,a,b,c)
# ---
# ## 5. Linear Algebra
# [<참고>선형대수 함수](https://rfriend.tistory.com/380)
# ### 5.1 Simple Array Operations
# In[ ]:
import numpy as np
a = np.array([[1.0, 2.0], [3.0, 4.0]])
print(a)
# In[ ]:
a.transpose()
# In[ ]:
np.linalg.inv(a)
# In[ ]:
u = np.eye(2) # unit 2x2 matrix; "eye" represents "I"
u
# In[ ]:
j = np.array([[0.0, -1.0], [1.0, 0.0]])
j
# In[ ]:
j @ j # matrix product
# In[ ]:
np.trace(u) # trace
# In[ ]:
y = np.array([[5.], [7.]])
y
# In[ ]:
np.linalg.solve(a, y)
# In[ ]:
np.linalg.eig(j)
# ---
# ## 6. Tricks and Tips
# ### 6.1 Automatic Reshaping
# In[ ]:
a = np.arange(30)
a
# In[ ]:
a.shape = 2,-1,3 # -1 means "whatever is needed"
a.shape
# In[ ]:
a
# ### 6.2 Vector Stacking
# In[ ]:
x = np.arange(0,10,2) # x=([0,2,4,6,8])
x
# In[ ]:
y = np.arange(5) # y=([0,1,2,3,4])
y
# In[ ]:
m = np.vstack([x,y]) # m=([[0,2,4,6,8],
m
# In[ ]:
xy = np.hstack([x,y]) # xy =([0,2,4,6,8,0,1,2,3,4])
xy
# ### 6.3 Histograms
# In[ ]:
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2
mu, sigma = 2, 0.5
v = np.random.normal(mu,sigma,10000)
# Plot a normalized histogram with 50 bins
plt.hist(v, bins=50, density=1) # matplotlib version (plot)
plt.show()
# In[ ]:
# Compute the histogram with numpy and then plot it
(n, bins) = np.histogram(v, bins=50, density=True) # NumPy version (no plot)
plt.plot(.5*(bins[1:]+bins[:-1]), n)
plt.show()
# ---
# In[ ]:
# end of file
# In[ ]:
반응형
LIST
'Programming' 카테고리의 다른 글
[Python][Library] 2 Pandas - 2. 파일 입출력 (0) | 2022.01.02 |
---|---|
[Python][Library] 2 Pandas - 1. 자료구조 (0) | 2022.01.02 |
[Python][Library] 1 Numpy - 배열과 벡터 (0) | 2022.01.02 |
[Python][문법] - 총 정리 (0) | 2021.12.30 |
[Python][문법] 개념 정리 (0) | 2021.12.26 |