Congratulation! Speed increase four times!
import time import numpy as np Iter = 1000000 A = np.array(['abcd','bcde','cdef','defg'] * Iter) Ti = time.time() B = np.zeros(A.size) for i in range(A.size): B[i] = ord(A[i][1]) * 256 + ord(A[i][2]) DT1 = time.time() - Ti Ti = time.time() ascii = A.astype('S') buff = ascii.view(np.uint8) result = buff[1::ascii.itemsize]*256 + buff[2::ascii.itemsize] DT2 = time.time() - Ti print("Equal = %s" % np.array_equal(B, result)) print("DT1=%7.2f Sec, DT2=%7.2f Sec, DT1/DT2=%6.2f" % (DT1, DT2, DT1/DT2))
Output:
Equal = True
DT1= 3.37 Sec, DT2= 0.82 Sec, DT1/DT2= 4.11