这一部分的主要内容:
a = np.random.randint(1, 10, (3,3))
print('Array a:')
print(a)
a =a - a.mean(axis=1, keepdims=True)
print('Result a:')
print(a)
输出:
Array a:
[[4 1 6]
[9 5 3]
[3 5 4]]
Result a:
[[ 0.33333333 -2.66666667 2.33333333]
[ 3.33333333 -0.66666667 -2.66666667]
[-1. 1. 0. ]]
注意numpy.mean()函数的调用格式:
numpy.mean(a, axis=None, dtype=None, out=None, keepdims= )
至于keepdims有什么作用,写个例子看一下就清楚了:
a = np.random.randint(1, 10, (3,3))
print('Array a:')
print(a)
print('keepdims = None')
print(a.mean(axis=1))
print('keepdims = True')
print(a.mean(axis=1, keepdims=True))
输出:
Array a:
[[7 8 1]
[4 2 9]
[6 7 4]]
keepdims = None
[5.33333333 5. 5.66666667]
keepdims = True
[[5.33333333]
[5. ]
[5.66666667]]
a = np.random.randint(1, 10, (3,3))
b = np.random.randint(1, 10, (3,3))
print('Array a:')
print(a)
print('Array b:')
print(b)
print('Result:')
print(np.diag(a.dot(b)))
输出:
Array a:
[[6 4 2]
[3 2 5]
[6 1 6]]
Array b:
[[7 5 4]
[5 5 8]
[8 2 6]]
Result:
[78 35 68]
这里样例中给出了更快速的两种方法:
a = np.random.randint(1, 10, (3,3))
b = np.random.randint(1, 10, (3,3))
print('Array a:')
print(a)
print('Array b:')
print(b)
print('Result:')
print(np.diag(a.dot(b)))
print('Result2:')
print(np.sum(a * b.T, axis=1))
print('Result3:')
print(np.einsum("ij, ji->i", a, b))
输出:
Array a:
[[2 7 3]
[8 7 4]
[1 2 9]]
Array b:
[[4 5 8]
[9 7 2]
[5 4 3]]
Result:
[ 86 105 39]
Result2:
[ 86 105 39]
Result3:
[ 86 105 39]
a = np.random.randint(1, 10, 5)
p = 3 #前p个最大值
print('Original array: ')
print(a)
b = sorted(a)[::-1]
print('Result:')
print(b[:p])
参考答案:
a = np.random.randint(1, 10, 5)
p = 3
print('Original array: ')
print(a)
print('Result:')
print(a[np.argsort(a)[-p:]])
输出:
Original array:
[1 5 9 2 3]
Result:
[3 5 9]
使用了argsort()函数,好吧,其实我学的还是不熟练。。。
使用数组可以很方便地对数组中所有的元素统一处理
a = np.random.randint(1, 10, 5)
print('Original array:')
print(a)
print('Result:')
print(np.power(a, 4))
输出:
Original array:
[6 3 2 4 5]
Result:
[1296 81 16 256 625]
a = np.random.uniform(0, 3, (2,2))
print('Original array:')
print(a)
print('Result:')
print(np.floor(a*100)/100)
输出:
Original array:
[[2.06304809 2.73927541]
[1.09291699 0.25479813]]
Result:
[[2.06 2.73]
[1.09 0.25]]
参考答案:
a = np.random.uniform(0, 3, (2))
print('Original array:')
print(a)
print('Result:')
np.set_printoptions(precision=2)
print(a)
直接设置了输出格式,但是接下来所有的输出都会有效,变为输出两位小数
a = np.random.random([3,3])
print(a/1e3) # 注意这里是数字1而非字母l
a = np.arange(15)
print('Array a:')
print(a)
print('Result:')
print(np.percentile(a, q=[25, 50, 75]))
输出:
Array a:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
Result:
[ 3.5 7. 10.5]