Santino
Santino

Reputation: 815

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.

Upvotes: 0

Views: 1627

Answers (2)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125284

If you mean the rectangle is stored in Postgresql as an array of points:

query = '''
    select array[(r[1])[0],(r[1])[1],(r[2])[0],(r[2])[1]]::int[]
    from (values ('{"(248,579)","(1,85)"}'::point[])) s (r)
'''

cursor.execute(query)
print cursor.fetchone()[0]

Returns a Python int list

[248, 579, 1, 85]

Notice that while a Postgresql array is base 1 by default, a Point coordinate is retrieved as a base 0 array.

Upvotes: 0

pferate
pferate

Reputation: 2107

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.

Upvotes: 2

Related Questions