Santino Santino - 2 months ago 14
Python Question

convert pgsql int array into python array

I have numeric data (int) stored in pgsql as arrays. These are

x,y,w,h
for rectangles in an image e.g.
{(248,579),(1,85)}


When reading to my python code (using psycopg) I get it as a string (?). I am now trying to find the best way to obtain a python array of ints from that string.
Is there a better way than to split the string on ',' and so on...

p.s. I did try
.astype(int)
construct but that wouldn't work in this instance.

Answer

Assuming that you wouldn't be able to change the input format, you could remove any unneeded characters, then split on the ,'s or do the opposite order.

data = '{(248,579),(1,85)}'
data.translate(None, '{}()').split(',')

will get you a list of strings.

And

[int(x) for x in data.translate(None, '{}()').split(',')]

will translate them to integers as well.