import numpy as np
a=np.array([100.,101.,102.,103.])
a.shape # 1차원 4개 요소
(4,)
a.ndim
1
a[0]
100.0
a[1]
101.0
a[-1]
103.0
a
array([100., 101., 102., 103.])
a[[1,3]]
array([101., 103.])
a[-3:-1]
array([101., 102.])
a[1:4:1]
array([101., 102., 103.])
a[1:4]
array([101., 102., 103.])
a[1:4:2]
array([101., 103.])
a[:]
array([100., 101., 102., 103.])
a[::2]
array([100., 102.])
a[::-2]
array([103., 101.])
a2=np.array([[11,12],[23 ,34]])
a2
array([[11, 12],
       [23, 34]])
a2.shape
(2, 2)
a2.ndim
2
a2[0][1] # 겉차원 -> 속차원
12
a2[0,1]
12
a
array([100., 101., 102., 103.])
a[[0,1]]
# 인덱스 0번쨰와 1번째 거 추출
array([100., 101.])
# 따라서 a2의 첫 번째 원소와 두 번째 원소만 추출됨
a2[[0,1]]
array([[11, 12],
       [23, 34]])
a2[:]
array([[11, 12],
       [23, 34]])
a2[:,:]
array([[11, 12],
       [23, 34]])

행렬처럼 생각하자

a2
array([[11, 12],
       [23, 34]])
a2[0,:]
array([11, 12])
a2[1,:]
array([23, 34])
b=a2[:,0]
b
array([11, 23])
b.shape
(2,)
b.ndim
1

b_=b[:,np.newaxis]
b_
array([[11],
       [23]])
b_.shape
(2, 1)
b_.ndim
2

또는

b.shape=(1,2)
b
array([[11, 23]])
a3=np.array([[[ 1,2],[3,4 ],[5,6 ],[7,8 ],[9,10]]])
a3
array([[[ 1,  2],
        [ 3,  4],
        [ 5,  6],
        [ 7,  8],
        [ 9, 10]]])
a3[0,0,1]
2
a3.shape
# 큰 덩어리 1개, 작은 덩어리 5개, 그 안에 요소 2개씩
(1, 5, 2)
a3.ndim #3차원
3
a3[0,1,1]
4
# 당연히 없을 것
# 큰 덩어리는 하나임
x=np.array([12,34,14,0,34])
idx=np.where(x==34)
idx
(array([1, 4], dtype=int64),)
x[idx]
array([34, 34])
idx=(x==14)
idx
array([False, False,  True, False, False])
x[idx]
array([14])
x[np.where(x==12)]
array([12])
x
array([12, 34, 14,  0, 34])
np.nonzero(x)
(array([0, 1, 2, 4], dtype=int64),)
x[np.nonzero(x)]
array([12, 34, 14, 34])
x==0
array([False, False, False,  True, False])
np.nonzero(x==14)
(array([2], dtype=int64),)
np.nonzero(x==0)
(array([3], dtype=int64),)
x[np.nonzero(x==0)]
array([0])
x[np.nonzero(x==34)]
array([34, 34])

image processing시, 논리연산을 통한 idexing 중요

image=np.array([[255,0,255],
              [255,0,255],
              [255,0,255]])
image.shape 
# 2차원, 큰덩어리 세개, 그 안에 요소 3개
(3, 3)
idx=np.where(image==255)
idx
(array([0, 0, 1, 1, 2, 2], dtype=int64),
 array([0, 2, 0, 2, 0, 2], dtype=int64))

(0,0)(0,2)(1,0)(1,2)(2,2) 자리에 255가 있다

image[idx]=0
image
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

이런식으로 논리연산을 통한 indexing으로 다 검정색을 만들어버림


a=np.array([[10,20],[30,40]])
b=np.array([[1,2],[3,4]])
a
array([[10, 20],
       [30, 40]])
b
array([[1, 2],
       [3, 4]])
a * b
array([[ 10,  40],
       [ 90, 160]])
a @ b
array([[ 70, 100],
       [150, 220]])
a.dot(b)
#행렬 연산
array([[ 70, 100],
       [150, 220]])
a=np.zeros((3,3))
a
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
b=np.ones((3,3))
b
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])
c=np.trace(b)
c
3.0

$x@a=y$ 에서 a행렬 구해보기

x=np.array([[1,-3],[2,4]])
y=np.array([[1],[3]])
print(x)
print(y)
[[ 1 -3]
 [ 2  4]]
[[1]
 [3]]
x_inverse=np.linalg.inv(x)
a=x_inverse@y
a
array([[1.3],
       [0.1]])

혹은

a=np.linalg.solve(x,y)
a
array([[1.3],
       [0.1]])

그 외에도 고유벡터, 고유값, 특이값 분해도 np에서 함수사용할 수 있다

a=np.zeros((5,5))
np.fill_diagonal(a,12)
a 
#대각원소만 12로 변경
array([[12.,  0.,  0.,  0.,  0.],
       [ 0., 12.,  0.,  0.,  0.],
       [ 0.,  0., 12.,  0.,  0.],
       [ 0.,  0.,  0., 12.,  0.],
       [ 0.,  0.,  0.,  0., 12.]])
a=np.array([[1,2,3],[3,4,4],[5,43,6]])
b=np.array([[1],[2],[3]])
b
array([[1],
       [2],
       [3]])
b=b.repeat(3,axis=1)
b
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])
  • 이제 원소대 원소 곱해주면 된다
c=a*b
c  
array([[  1,   2,   3],
       [  6,   8,   8],
       [ 15, 129,  18]])
  • broadcasting : size알아서 처리해주는 기능
a
array([[ 1,  2,  3],
       [ 3,  4,  4],
       [ 5, 43,  6]])
b=np.array([[1],[2],[3]])
b
array([[1],
       [2],
       [3]])
a*b
array([[  1,   2,   3],
       [  6,   8,   8],
       [ 15, 129,  18]])

def f(x,y):
    return 100*x+y
np.fromfunction(f,(4,4),dtype=int)
array([[  0,   1,   2,   3],
       [100, 101, 102, 103],
       [200, 201, 202, 203],
       [300, 301, 302, 303]])
  • 행이 x축 역할하고 열이 y축 역할을 함으로써, 격자로 더해준다고 생각하면 됨

a=np.array([10,20,30,40,50])
b=np.array([30,50])
np.setdiff1d(a,b)
array([10, 20, 40])

np.random.randint(54)
26

import matplotlib.pyplot as plt
y=np.array([10,20,30])
plt.plot(y)
[<matplotlib.lines.Line2D at 0x1ed34d292b0>]
x=np.array([123,413,555])
plt.plot(x,y,'r--.')
#data가 들어간 곳에 dot으로 표시
[<matplotlib.lines.Line2D at 0x1ed34e3d160>]
plt.plot(x,y,'b-o',label='fuck')
plt.ylabel('sd')
plt.xlabel('SD')
plt.legend()
plt.title('What\'s this?')
Text(0.5, 1.0, "What's this?")
hf=plt.figure() # 도화지
ha1 = hf.add_axes([0,0,1,1]) # 0,0자리에 1,1크기만큼
ha2 = hf.add_axes([1,1,1,1]) # 0,0자리에 1,1크기만큼
ha1.plot(x,y,'o-r')
ha2.plot(x,y,'x:b')
[<matplotlib.lines.Line2D at 0x1ed37a58430>]
aa,bb=plt.subplots()
hong,=bb.plot(x,y)
# 이렇게 aa,bb는 임의로 지명 가능
  • 위 그래프 update
a_new=np.array([200,331,335])
b_new=np.array([10,50,10])
hong.set_data(a_new,b_new)
aa

주의 :애초에 aa라는 도화지에 정해진 축이 있기 때문에 그 축에서 너무 멀어지는 값들을 넣어주면 aa라는 도화지에 보이지 않을 수 있음

PLUS=1.5
a_new=np.array([200,331,335])
b_new=np.array([10,50,10])
hong.set_data(a_new,PLUS*b_new)
aa

그래프가 올라간 것을 확인할 수 있음

a=np.linspace(0,2,100)
y1=0.5*a
y2=0.5*a**2
y3=0.5*a**3
plt.plot(a,y1,label='1D')
plt.plot(a,y2,label='2D')
plt.plot(a,y3,label='3D')
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('GRAPH')
Text(0.5, 1.0, 'GRAPH')
fig,ax=plt.subplots()
ax1,=ax.plot(a,y1) # comma 입력해주면 나중에 update 가능
ax2,=ax.plot(a,y2)
ax3,=ax.plot(a,y3)
ax.set_xlabel('X') # plt가 아닐 땐 set을 입력해줘야 함
ax.set_ylabel('Y')
ax1.set_label('1')
ax2.set_label('2')
ax3.set_label('3')
ax.legend()
<matplotlib.legend.Legend at 0x1ed37aa5e20>
ax1.set_color('k')
ax2.set_color('b')
ax3.set_color('r')
ax.grid()
ax.legend()
fig

decay sin

t=np.linspace(0,100,1000)
tau= 60
y=np.sin(t)*np.exp(-t/tau)
plt.plot(t,y,label='Decay Oscillating Response')
plt.ylabel('y[m]')
plt.xlabel('t[s]')
plt.legend()
<matplotlib.legend.Legend at 0x1ed36bc0070>

Euler eq

t=np.linspace(0,1,100)
f= 1 # 주파수
y_euler=np.exp(1j*2*np.pi**f*t)
y_cos = np.real(y_euler)
y_sin=np.imag(y_euler)
fig,ax=plt.subplots()
ax.plot(t,y_cos,'-r',label='cos')
ax.plot(t,y_sin,'--b',label='sin')
ax.grid()
ax.legend()
<matplotlib.legend.Legend at 0x1ed36cbe280>
fig,ax=plt.subplots(2,)
ax[0].plot(t,y_cos,'-r',label='cos')
ax[1].plot(t,y_sin,'--b',label='sin')
ax[0].grid()
ax[0].legend()
ax[1].grid()
ax[1].legend()
<matplotlib.legend.Legend at 0x1ed38d1e850>

Histogram

data=np.random.randn(500000)
plt.hist(data,100,density=True) # 100개의 막대로 나누겠다, 확률밀도함수로 그리겠다
x=np.linspace(-4,4,100)
sigma=1
mean=0
nd=(1/(sigma*np.sqrt(2*np.pi)))*np.exp(-0.5*((x-mean)/sigma)**2)
plt.plot(x,nd,'r',label='Std Normal Dist')
plt.ylabel('PSD')
plt.xlabel('X')
plt.legend()
<matplotlib.legend.Legend at 0x1ed3929cfd0>

3D plot

x=np.linspace(0,2*np.pi,10)
y=np.linspace(0,2*np.pi,10)
grid_x,grid_y=np.meshgrid(x,y) # 1차원 array를 통해 2차원 grid를 만들어줌
z=np.sin(grid_x)*np.sin(grid_y)
fig=plt.figure()
ax=fig.gca(projection='3d') # Get Current Axis=gca
ax.plot_surface(grid_x,grid_y,z,cmap='jet')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
C:\Users\ehfus\AppData\Local\Temp/ipykernel_20060/1177705184.py:6: MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current axes, or if no axes exist, create new axes with default keyword arguments. To create a new axes with non-default arguments, use plt.axes() or plt.subplot().
  ax=fig.gca(projection='3d') # Get Current Axis=gca
Text(0.5, 0, 'z')

Animation

# x=np.array([1,2,3,4,5])
# y=np.array([1,1,1,1,1])
# ax1, = ax.plot(x,y)
# ax.set_ybound([0,11])
# for i in range(0,11,1):
#     ax1.set_ydata(i*y)
#     plt.pause(0.3)
# 원래는 animation기능으로 움직여야 함