Python/Numpy
[ Numpy 100제 ] 01 ~ 10 번
teang1995
2021. 10. 1. 13:20
반응형
numpy 핸들링에 익숙해져야 한다고 생각해서.. 마침 누군가 잘 만들어둔 numpy 100제 문제가 있어 조금씩 풀어보려 한다.
01. import numpy package under the name np
import numpy as np
너무 많이 써봤던 코드다.
02.Print the numpy version and the configuration
np.__version__
# '1.21.0'
numpy 버전을 체크해본 적은 없지만, 당연히 이렇게 될 것이라 짐작할 수 있었다.
03. Create a null vector of size 10
a = np.zeros(10)
a
# array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
어렵지 않게 구할 수 있었다.
04. How to find the memory size of any array
a = np.zeros(100)
num_items = a.size
size_items = a.itemsize
print(f'num_items : {num_items}')
print(f'size_items : {size_items}')
print(f'memory_size : {num_items * size_items}')
# num_items : 100
# size_items : 8
# memory_size : 800
모르는 게 나왔다.
np.size 까지는 사용해봤는데, itemsize 는 처음 본다.
numpy 행렬의 장점인 모든 요소에 같은 자료형과 용량이 할당되는 점을 이용해 길이와 itemsize를 곱해주면 쉽게 구할 수 있었다.
05. How to get the documentation of the numpy add function from the command line?
np.info('add')
*** Found in numpy ***
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
add : ndarray or scalar
The sum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
...
워후 이런 게 있었다.
종종 사용할 듯 ㅎㅎ
06. Create a null vector of size 10 but the fifth value which is 1
# my solution
a = [1.0 if i == 4 else 0.0 for i in range(10)]
a = np.array(a)
print(a)
# solution
a = np.zeros(10)
a[4] = 1
print(a)
내 풀이와 문제를 낸 사람의 풀이가 갈렸는데, numpy array, tensor 로 바꾼 뒤에는 인덱스 접근을 하지 않으면 좋을 것 같아서..
07. Create a vector with value ranging from 10 to 49
a = np.arange(10, 50)
a
'''
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49])
'''
자주 사용해봤던 친구라 어렵지 않았다.
08. Reverse a vector (first element becomes last)
a = np.arange(0, 10)
a[::-1]
# array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
::-1 을 주어 step을 -1로 바꿔주었다. 이렇게 역순의 array를 얻을 수 있게 된다!
09. Create 3x3 matrix with values ranging from 0 to 8
a = np.arange(0, 9)
a = a.reshape(3, -1)
a
'''
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
'''
-1을 인자로 넣어주면
"야, 행은 3개야. 그럼 열은 몇개인지 알아서 계산해"하는 옵션을 줄 수 있다.
어렵지 않았다.
10. Find indices of non-zero elements from [1, 2, 0, 0, 4, 0]
a = np.array([1, 2, 0, 0, 4, 0])
np.nonzero(a) # awesome
# array([0, 1, 4]),)
자주 사용하게 될 것 같다. 몰랐는데 찾아봤더니 이런 멋진 게 있더라.