numpy数组的索引和切片
基本切片操作
>>> import numpy as np
>>> arr=np.arange(10)
>>> arr
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> arr[5]
5
>>> arr[5:8]
array([5, 6, 7])
切片赋值操作
1.切片赋一个值对应原来数组中的值也会变
>>> arr[5:8]=12
>>> arr
array([ 0, 1, 2, 3, 4, 12, 12, 12, 8, 9])
>>> import numpy as np
>>> arr=np.arange(10)
>>> arr_slice=arr[5:8]
>>> arr_slice[0]=-1
>>> arr_slice
array([-1, 6, 7])
>>> arr
array([ 0, 1, 2, 3, 4, -1, 6, 7, 8, 9])
2.给数组中所有元素赋值
>>> arr[:]=-1
>>> arr
array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1])
3.如果想使用复制的方法,使用copy方法
>>> arr_copy=arr[:].copy()
>>> arr_copy
array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1])
>>> arr_copy[:]=0
>>> arr_copy
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> arr
array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1])
高阶数组索引
>>> import numpy as np
>>> arr2d=np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> arr2d[2]
array([7, 8, 9])
>>> arr2d[0][2]
3
>>> arr2d[0,2]
3
>>> import numpy as np
>>> arr2d=np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> arr2d[2]
array([7, 8, 9])
>>> arr2d[0][2]
3
>>> arr2d[0,2]
3
>>> arr3d=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
>>> arr3d
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
>>> arr3d[0]
array([[1, 2, 3],
[4, 5, 6]])
>>> old_values=arr3d[0].copy()
>>> arr3d[0]=42
>>> arr3d
array([[[42, 42, 42],
[42, 42, 42]],
[[ 7, 8, 9],
[10, 11, 12]]])
>>> arr3d[1,0]
array([7, 8, 9])
>>> x=arr3d[1]
>>> x
array([[ 7, 8, 9],
[10, 11, 12]])
>>> x[0]
array([7, 8, 9])
高维数组切片
>>> arr2d[:2]
array([[1, 2, 3],
[4, 5, 6]])
>>> arr2d[:2,1:]
array([[2, 3],
[5, 6]])
>>> arr2d[1,:2]
array([4, 5])
>>> arr2d[:2,2]
array([3, 6])
>>> arr2d[:,:1]
array([[1],
[4],
[7]])
原文地址:https://www.cnblogs.com/mengxiaoleng/p/11616869.html
时间: 2024-12-28 21:41:02