Skip to content

Comparison with Numpy

Nathan Jenkins edited this page Jul 7, 2018 · 6 revisions

Comparison with Numpy:

Indexing (at a glance)

  • Numpy:
a[ 0, ... , 1:5, 1: , ::-1, numpy.newaxis, : ]
  • Numo::NArray:
a[ 0, false, 1..4, 1..-1, (-1..0).step(-1), :new, true ]

Indexing (one to one)

* Single Element
 numpy:  a[0]
 numo:   a[0]
* Last element
 numpy:  a[-1]
 numo:   a[-1]
* Range
 numpy:  a[2:6]
 numo:   a[2..5]
* Range upto
 numpy:  a[:6]
 numo:   a[0..5]
* Range beginning with
 numpy:  a[2:]
 numo:   a[2..-1]
* All elements along axis:
 numpy:  a[1, :]
 numo:   a[1, true]
* Step
 numpy:  a[::2]
 numo:   a[(0..-1).step(2)]
* Reverse
 numpy:  a[::-1]
 numo:   a[(-1..0).step(-1)]
* Ellipsis axes
 numpy:  a[..., 2]
 numo:   a[false, 2]
* New axis
 numpy:  a[0, numpy.newaxis, 0]
 numo:   a[0, :new, 0]

1-D indexing on 2-D array

  • Numpy
>>> import numpy as np
>>> x = np.arange(12).reshape(3,4)
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

>>> x[1,...]
array([4, 5, 6, 7])

>>> x[1]
array([4, 5, 6, 7])

>>> x[1:3]
array([[ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

>>> x[8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 8 is out of bounds for axis 0 with size 3
  • Numo::NArray
irb(main):001:0> x = Numo::DFloat.new(3,4).seq
=> Numo::DFloat#shape=[3,4]
[[0, 1, 2, 3], 
 [4, 5, 6, 7], 
 [8, 9, 10, 11]]

irb(main):002:0> x[1,false]
=> Numo::DFloat(view)#shape=[4]
[4, 5, 6, 7]

irb(main):003:0> x[1]
=> 1.0

irb(main):004:0> x[1..2]
=> Numo::DFloat(view)#shape=[2]
[1, 2]

irb(main):005:0> x[8]
=> 8.0

irb(main):006:0> x[8..10]
=> Numo::DFloat(view)#shape=[3]
[8, 9, 10]