如果想在 V2EX 获得更好的推广效果,欢迎了解 PRO 会员机制:
https://www.v2ex.com/pro/about

如果你经常使用铜币置顶主题,持有 V2EX Solana Token 会在每日签到时获得额外铜币:
https://www.v2ex.com/solana
fanqieipnet
V2EX  ›  推广

如何利用 NumPy 进行索引和切片?

  •  
  •   fanqieipnet · Dec 16, 2020 · 901 views
    This topic created in 1986 days ago, the information mentioned may be changed or developed.
    处理多维数组,如何利用 NumPy 进行索引和切片?今天番茄加速就来跟大家讲解下。

      平时遇到关于 NumPy 的 bug,解决不了的,可以先去查看 API 的使用说明。

      理解 NumPy 的向量化能力,这正是赋予它简洁的重要原因之一。使用 Python 原生 API 会经常写些 for,但是 NumPy 让它变得不再需要,NumPy 一切都是按照向量计算。如下计算小于 3 的元素置 0,否则置为 1:

      # 使用 Python 原生

       a = [10,4,-6,3,5,1]

      # 小于 3 的元素置为 0,不小于 3 的元素置为 1

       b = []

       for i in a:

       b.append(0 if i < 3 else 1)

       print(b)

      使用 NumPy 的 where 方法,语法更加简洁,看不到 for 语句,符合 Python 哲学:

      # 使用 NumPy

       na = np.array(a)

      # 一行代码

       b = np.where(na < 3, 0, 1)

       print(b)

       3. 处理多维数组,NumPy 的索引和切片更强大,如下 na < 3 得到布尔索引,一切都按照向量化操作:

       na = np.array([10,4,-6,3,5,1])

       na[na < 3]

      # 结果如下:

      # array([-6, 1])

      # 创建二维数组

       np.random.randint(1,10,size=(3,4))

       c2 = np.random.randint(1,10,size=(3,4))

       c2

       array([[3, 2, 9, 9],

      [9, 5, 2, 4],

      [8, 1, 2, 4]])

      # 更强大简洁的切片功能:

       c2[:2,1:3]

       array([[2, 9],

      [5, 2]])
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1016 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 22:32 · PVG 06:32 · LAX 15:32 · JFK 18:32
    ♥ Do have faith in what you're doing.