Numpy学习|索引:
文章目录
1.副本与视图
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = x.copy()
y[0] = -1
print(x)
# [1 2 3 4 5 6 7 8]
print(y)
# [-1 2 3 4 5 6 7 8]
2.索引与切片
x = np.array([[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]])
print(x[::2, ::2])
# 首:尾:间隔
# [[11 13 15]
# [21 23 25]
# [31 33 35]]
x = np.array([[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]])
x[0::2, 1::3] = 0
print(x)
# 0行,2行,4行的 2、5列赋值为0
# [[11 0 13 14 0]
# [16 17 18 19 20]
# [21 0 23 24 0]
# [26 27 28 29 30]
# [31 0 33 34 0]]
x = np.array([[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]])
r = [0, 1, 2]
c = [2, 3, 4]
y = np.take(x, [r, c])
print(y)
# [[11 12 13]
# [13 14 15]]
3.数组迭代
除了for循环,Numpy 还提供另外一种更为优雅的遍历方法。
apply_along_axis(func1d, axis, arr) Apply a function to 1-D slices along the given axis.
import numpy as np
x = np.array([[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]])
y = np.apply_along_axis(np.sum, 0, x)
print(y) # [105 110 115 120 125]
y = np.apply_along_axis(np.sum, 1, x)
print(y) # [ 65 90 115 140 165]
y = np.apply_along_axis(np.mean, 0, x)
print(y) # [21. 22. 23. 24. 25.]
y = np.apply_along_axis(np.mean, 1, x)
print(y) # [13. 18. 23. 28. 33.]
def my_func(x):
return (x[0] + x[-1]) * 0.5
y = np.apply_along_axis(my_func, 0, x)
print(y) # [21. 22. 23. 24. 25.]
y = np.apply_along_axis(my_func, 1, x)
print(y) # [13. 18. 23. 28. 33.]
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/165191.html