Numpy

[Numpy] Operation_function, Concatenate

ju_young 2021. 7. 16. 13:23
728x90
In [2]:
import numpy as np
 
In [4]:
test_array = np.arange(1, 11)
test_array
Out[4]:
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Sum

In [6]:
test_array.sum(dtype=np.float)
Out[6]:
55.0
 
In [9]:
test_array = np.arange(1, 13).reshape(3,4)
test_array.sum()
 
Out[9]:
78
 
In [12]:
print(test_array)
test_array.sum(axis=1) #칼럼끼리 더한다
 
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
Out[12]:
array([10, 26, 42])
 
In [14]:
test_array.sum(axis=0) #행끼리 더한다
Out[14]:
array([15, 18, 21, 24])
 
In [17]:
third_order_tensor = np.array([test_array, test_array, test_array])
third_order_tensor
Out[17]:
array([[[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]],

       [[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]],

       [[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]]])
 
In [19]:
third_order_tensor.sum(axis=2) #column
Out[19]:
array([[10, 26, 42],
       [10, 26, 42],
       [10, 26, 42]])
 
In [21]:
third_order_tensor.sum(axis=1) #row
Out[21]:
array([[15, 18, 21, 24],
       [15, 18, 21, 24],
       [15, 18, 21, 24]])
 
In [23]:
third_order_tensor.sum(axis=0) #level
Out[23]:
array([[ 3,  6,  9, 12],
       [15, 18, 21, 24],
       [27, 30, 33, 36]])
 
In [25]:
test_array = np.arange(1, 13).reshape(3, 4)
test_array
Out[25]:
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

Mean

In [27]:
test_array.mean(), test_array.mean(axis=0) #평균
Out[27]:
(6.5, array([5., 6., 7., 8.]))

Std

In [29]:
test_array.std(), test_array.std(axis=0) #표준편차
Out[29]:
(3.452052529534663, array([3.26598632, 3.26598632, 3.26598632, 3.26598632]))

Exp, Sqrt

In [31]:
np.exp(test_array), np.sqrt(test_array) #지수, 제곱근
Out[31]:
(array([[2.71828183e+00, 7.38905610e+00, 2.00855369e+01, 5.45981500e+01],
        [1.48413159e+02, 4.03428793e+02, 1.09663316e+03, 2.98095799e+03],
        [8.10308393e+03, 2.20264658e+04, 5.98741417e+04, 1.62754791e+05]]),
 array([[1.        , 1.41421356, 1.73205081, 2.        ],
        [2.23606798, 2.44948974, 2.64575131, 2.82842712],
        [3.        , 3.16227766, 3.31662479, 3.46410162]]))

vstack, hstack

In [33]:
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
np.vstack((a, b)) #vertical 방향으로 합침
Out[33]:
array([[1, 2, 3],
       [2, 3, 4]])
 
In [37]:
a = np.array([[1], [2], [3]])
b = np.array([[2], [3], [4]])
np.hstack((a,b)) #horizontal 방향으로 합침
Out[37]:
array([[1, 2],
       [2, 3],
       [3, 4]])

concatenate

In [39]:
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
np.concatenate((a, b), axis=0) #1차원 array이므로 row끼리 합쳐짐
Out[39]:
array([1, 2, 3, 2, 3, 4])
In [43]:
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
np.concatenate((a, b.T), axis=1) #열끼리 합쳐짐
Out[43]:
array([[1, 2, 5],
       [3, 4, 6]])

tolist()

In [44]:
a.tolist()
Out[44]:
[[1, 2], [3, 4]]
728x90