Python Numpy Exercise (2)
2023. 1. 22. 01:36ㆍ파이썬
Numpy Exercising (2)¶
In [5]:
import numpy as np
import sys
Performance is also important¶
In [10]:
l = list(range(100000))
In [11]:
a = np.arange(100000)
In [12]:
%time np.sum(a ** 2)
Wall time: 990 µs
Out[12]:
216474736
In [13]:
%time sum(x**2 for x in l)
Wall time: 82.5 ms
Out[13]:
333328333350000
Several Useful Numpy Functions¶
Random¶
Literally Random sample¶
In [14]:
np.random.random(size=2)
Out[14]:
array([0.54876149, 0.59113263])
Making Normal distribution sample¶
In [15]:
np.random.normal(size=2)
Out[15]:
array([-0.79644299, 1.31142929])
From 0 to 1, Making a normal distribution matrix array¶
In [16]:
np.random.rand(2,4)
Out[16]:
array([[0.55791742, 0.65970045, 0.85331649, 0.27839654], [0.14893521, 0.93210058, 0.93941279, 0.02274239]])
Arange¶
In [17]:
np.arange(3)
Out[17]:
array([0, 1, 2])
In [18]:
np.arange(2,7)
Out[18]:
array([2, 3, 4, 5, 6])
Reshape¶
In [20]:
np.arange(10).reshape(2,5)
Out[20]:
array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
In [21]:
np.arange(6).reshape(2,3)
Out[21]:
array([[0, 1, 2], [3, 4, 5]])
In [22]:
np.arange(10).reshape(5,2)
Out[22]:
array([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]])
Linspace¶
In [23]:
np.linspace(0,1,5)
Out[23]:
array([0. , 0.25, 0.5 , 0.75, 1. ])
In [24]:
np.linspace(0,1,20)
Out[24]:
array([0. , 0.05263158, 0.10526316, 0.15789474, 0.21052632, 0.26315789, 0.31578947, 0.36842105, 0.42105263, 0.47368421, 0.52631579, 0.57894737, 0.63157895, 0.68421053, 0.73684211, 0.78947368, 0.84210526, 0.89473684, 0.94736842, 1. ])
In [25]:
np.linspace(0, 1, 20, False)
Out[25]:
array([0. , 0.05, 0.1 , 0.15, 0.2 , 0.25, 0.3 , 0.35, 0.4 , 0.45, 0.5 , 0.55, 0.6 , 0.65, 0.7 , 0.75, 0.8 , 0.85, 0.9 , 0.95])
Zeros, Ones, Empty¶
In [26]:
np.zeros(5)
Out[26]:
array([0., 0., 0., 0., 0.])
In [27]:
np.zeros((3,3))
Out[27]:
array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])
In [30]:
np.zeros((3,6))
Out[30]:
array([[0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0.]])
In [31]:
np.ones(5)
Out[31]:
array([1., 1., 1., 1., 1.])
In [32]:
np.ones((4,4))
Out[32]:
array([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]])
In [33]:
np.empty(5)
Out[33]:
array([1., 1., 1., 1., 1.])
np.empty((2,2))
Identity and eye¶
In [35]:
np.identity(3)
Out[35]:
array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
In [36]:
np.eye(3,3)
Out[36]:
array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
In [37]:
"Hello World"[3]
Out[37]:
'l'
In [38]:
np.eye(8,4)
Out[38]:
array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])
In [40]:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
'파이썬' 카테고리의 다른 글
Python Numpy Exercise (1) (0) | 2023.01.21 |
---|---|
Data Analysis (0) | 2023.01.20 |