Would you use numpy if you were just manipulating a sequence of binary values?

Is there any advantage to using numpy when doing a lot of operations on lists of binary values? What about integers within a small range (e.g., numbers 1,2 and 3?)

+3
source share
2 answers

Cycle elimination is a source of performance boost (10x):

import profile
import numpy as NP

def np_test(a2darray) :
  row_sums = NP.sum(a2darray, axis=1)
  return NP.sum(row_sums)

def stdlib_test2(a2dlist) :
  return sum([sum(row) for row in a2dlist])

A = NP.random.randint(1, 6, 1e7).reshape(1e4, 1e3)
B = NP.ndarray.tolist(A)

profile.run("np_test(A)")
profile.run("stdlib_test2(B)")

Numpy

  • 10 function calls in 0.025 CPU seconds

lists

  • 10005 function calls in 0.280 CPU seconds
+3
source

, bitarray, . Dtype bool/int8/uint8 Numpy ndarray:

In [1]: import numpy as np
In [2]: data = np.array([0,1,1,0], dtype=bool)
In [3]: data
Out[3]: array([False,  True,  True, False], dtype=bool)
In [4]: data.size
Out[4]: 4
In [5]: data.nbytes
Out[5]: 4
+1

Source: https://habr.com/ru/post/1733634/


All Articles