-1

Can Numpy be used to do faster string assignment?

I want my string array like

[['x1-y1', 'x1-y2'...],
['x2-y2, 'x2-y2' ...],
.....
]

so on

So, the string at every (i,j) = "x%d-y%d" % (i,j)

Can this be done in Numpy?

1 Answer 1

0

If the size of your array is (m,m)

rx = np.outer(np.ones((m,)), np.linspace(1, m, m))
ry = np.outer(np.linspace(1, m, m), np.ones((m,)))
s1 = np.chararray((m, m),itemsize=1)
s1[:]=''
strarray = s1+'x'+np.array(rx, dtype='str')+'-'+'y'+np.array(ry, dtype='str')

Output would be

chararray([['x1.0-y1.0', 'x2.0-y1.0', 'x3.0-y1.0', 'x4.0-y1.0', 'x5.0-y1.0'],
       ['x1.0-y2.0', 'x2.0-y2.0', 'x3.0-y2.0', 'x4.0-y2.0', 'x5.0-y2.0'],
       ['x1.0-y3.0', 'x2.0-y3.0', 'x3.0-y3.0', 'x4.0-y3.0', 'x5.0-y3.0'],
       ['x1.0-y4.0', 'x2.0-y4.0', 'x3.0-y4.0', 'x4.0-y4.0', 'x5.0-y4.0'],
       ['x1.0-y5.0', 'x2.0-y5.0', 'x3.0-y5.0', 'x4.0-y5.0', 'x5.0-y5.0']], 
      dtype='|S68')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.