numpy索引、切片

基础操作

import numpy as np

x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x[1:7:2]   # start:end:step  
array([1, 3, 5])
x[-2:10]
array([8, 9])
x[-3:3:-1]  # 逆序取值  常规逆序输出 [::-1]
array([7, 6, 5, 4])
x[5:]
array([5, 6, 7, 8, 9])
# 多维切片
x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
x.shape

(2, 3, 1)
x[1:2]  # [:,:,:]  ":",对应每一维度, 单独维度可以进行 一维操作 :::
array([[[4],
        [5],
        [6]]])
x[..., 0]
array([[1, 2, 3],
       [4, 5, 6]])
x[:, np.newaxis, :, :].shape  # 添加维度
(2, 1, 3, 1)
x = np.array([[1, 2], [3, 4], [5, 6]])
x[[0, 1, 2], [0, 1, 0]]  # 按位置取值
array([1, 4, 5])
x = np.array([[ 0,  1,  2],
              [ 3,  4,  5],
              [ 6,  7,  8],
              [ 9, 10, 11]])
rows = np.array([[0, 0],
                 [3, 3]], dtype=np.intp)
columns = np.array([[0, 2],
                    [0, 2]], dtype=np.intp)
x[rows, columns]
array([[ 0,  2],
       [ 9, 11]])
rows = np.array([0, 3], dtype=np.intp)
columns = np.array([0, 2], dtype=np.intp)
rows[:, np.newaxis]
array([[0],
       [3]], dtype=int64)
x[rows[:, np.newaxis], columns]
array([[ 0,  2],
       [ 9, 11]])
x[np.ix_(rows, columns)]
array([[ 0,  2],
       [ 9, 11]])
# 混合索引
x[1:2, 1:3]
array([[4, 5]])
x[1:2, [1, 2]]
array([[4, 5]])

布尔索引

x = np.array([[1., 2.], [np.nan, 3.], [np.nan, np.nan]])
x[~np.isnan(x)]
array([1., 2., 3.])
x = np.array([1., -1., -2., 3])
x[x < 0] += 20
x
array([ 1., 19., 18.,  3.])
x = np.array([[0, 1], [1, 1], [2, 2]])
rowsum = x.sum(-1)
x[rowsum <= 2, :]
array([[0, 1],
       [1, 1]])
x = np.array([[ 0,  1,  2],
              [ 3,  4,  5],
              [ 6,  7,  8],
              [ 9, 10, 11]])
rows = (x.sum(-1) % 2) == 0
rows
array([False,  True, False,  True])
columns = [0, 2]
x[np.ix_(rows, columns)]
array([[ 3,  5],
       [ 9, 11]])
rows = rows.nonzero()[0]
x[rows[:, np.newaxis], columns]
array([[ 3,  5],
       [ 9, 11]])
x = np.zeros((2,2), dtype=[('a', np.int32), ('b', np.float64, (3,3))])
x['a'].shape
(2, 2)
x['a'].dtype
dtype('int32')
x['b'].shape
(2, 2, 3, 3)
x['b'].dtype
dtype('float64')

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 索引和切片 一维数组 一维数组很简单,基本和列表一致。它们的区别在于数组切片是原始数组视图(这就意味着,如果做任何...
    云间书吏阅读 1,589评论 0 1
  • 基本的索引和切片 切片[ : ]会给数组中的所有值赋值 ndarray切片的一份副本而非视图,就需要明确地进行复制...
    GHope阅读 1,947评论 0 5
  • 1---一维数组索引及切片 2---二维数组索引及切片 3---布尔型索引及切片 布尔型 条件判断
    夏日春风阅读 246评论 0 2
  • 接一章 python:numpy的索引和切片(1)python:numpy的索引和切片(1) 1、numpy中数值...
    书生_Scholar阅读 142评论 0 1
  • import numpy as np 01一维数组 一维数组的 索引和切片 a = np.arange(9) 3-...
    小螳螂阅读 230评论 0 1