15.Numpy之点乘、算术运算、切片、遍历和下标取值

# Numpy之 点乘、算术运算、切片、遍历和下标取值
import numpy as np

a = np.arange(4)
b = np.arange(4, 11, 2)
print(a)
print(b)

a_plus_b = a + b
print(a_plus_b)
a_multiplication_b = a * b
print(a_multiplication_b)

boolean_arr = b < 7
print(boolean_arr)

# 对数组a中所有元素加一
a += 1
print(a)

aa = np.array([[1, 2], [3, 4]])
bb = np.array([[1, 2], [3, 4]])

# 对应元素相乘
print(aa * bb)
# 矩阵乘法
print(aa.dot(bb))

random_arr = np.random.random((2, 3))

print(random_arr)

sum_random = random_arr.sum()
print('sum of array: ', sum_random)

print('minimum value of array: ', random_arr.min())
print('maximum value of array: ', random_arr.max())

print(random_arr.min(axis=0))
print(random_arr.min(axis=1))

# 一维数组的切片、根据下标取值和用迭代器遍历功能跟列表等序列相同
print(a)  # [1 2 3 4]
print(a[1:3])  # [2 3]
print(a[-1])  # 4
for x in a:
    print(x)
# output:
# 1
# 2
# 3
# 4

# 多维数组的切片、根据下标取值和用迭代器遍历功能

b = np.array([[1, 2, 3, 4, 5], [11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35], [41, 42, 43, 44, 45]])
print('traversal array and treat it as one dimensional array:')
for x in b:
    print(x, end=",")
print()
# output:
# [1 2 3 4 5],[11 12 13 14 15],[21 22 23 24 25],[31 32 33 34 35],[41 42 43 44 45],
print('traversal array for every element:')
for x in b:
    for y in x:
        print(y, end=" ")
print()
# output:
# 1 2 3 4 5 11 12 13 14 15 21 22 23 24 25 31 32 33 34 35 41 42 43 44 45

print('Slice the multidimensional array 1:')
print(b[:, 1])
print('Slice the multidimensional array 2:')
print(b[1:3, :])
# output:
# Slice the multidimensional array 1:
# [ 2 12 22 32 42]
# Slice the multidimensional array 2:
# [[11 12 13 14 15]
#  [21 22 23 24 25]]

# ...的用法
c = np.array([[[1, 2, 3], [11, 12, 13]], [[4, 5, 6], [14, 15, 16]], [[7, 8, 9], [17, 18, 19]]])
print(c[1, ...])  # 相当于c[1,:,:]
# output:
# [[ 4  5  6]
#  [14 15 16]]

print(c[..., 2])  # 等价于c[:,:,2]
# output:
# [[ 3 13]
#  [ 6 16]
#  [ 9 19]]
原文地址:https://www.cnblogs.com/wjc920/p/9256149.html