This is a continuation of the previous article. #Python basics (#Numpy 1/2) The environment uses the environment created in the previous article. → Building Anaconda python environment on Windows 10
Convert a 1-by-6 array to a 2-by-3 array
import numpy as np
a = np.array([0,1,2,3,4,5])
b = a.reshape(2,3)
print(b)
Execution result
[[0 1 2]
[3 4 5]]
By setting the argument of reshape to -1, you can convert an array of any shape to a one-dimensional array.
import numpy as np
c = np.array([[[0, 1, 2],
[3, 4, 5]],
[[5, 4, 3],
[2, 1, 0]]]) #Create a 3D array of NumPy from a triple list
print(c)
print("--------------------------")
d = c.reshape(-1)
print(d)
Execution result
[[[0 1 2]
[3 4 5]]
[[5 4 3]
[2 1 0]]]
--------------------------
[0 1 2 3 4 5 5 4 3 2 1 0]
Access to each element of ndarray
specifies the index as well as list
.
One-dimensional array
import numpy as np
a = np.array([0, 1, 2, 3, 4, 5])
print(a[2])
# 2
Multidimensional array
b = np.array([[0, 1, 2],
[3, 4, 5]])
print(b[1, 2]) # b[1][2]Same as
print(b[1][2])
# 5
# 5
import numpy as np
def func_a(x):
y = x * 2 + 1
return y
a = np.array([[0, 1, 2],
[3, 4, 5]]) #A two-dimensional array
b = func_a(a) #Pass an array as an argument
print(b)
Execution result
[[ 1 3 5]
[ 7 9 11]]
3.sum, average, max, min
import numpy as np
a = np.array([[0, 1, 2],
[3, 4, 5]]) #A two-dimensional array
print("sum : ",np.sum(a))
print("average : ",np.average(a))
print("max : ",np.max(a))
print("min : ",np.min(a))
Execution result
sum : 15
average : 2.5
max : 5
min : 0
import numpy as np
b = np.array([[0, 1, 2],
[3, 4, 5]]) #A two-dimensional array
print('axis=0 : ',np.sum(b, axis=0)) #Total in the vertical direction
print('axis=1 : ',np.sum(b, axis=1)) #Total in the horizontal direction
Execution result
axis=0 : [3 5 7]
axis=1 : [ 3 12]
Recommended Posts