0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! I was hoping to go thus route, hoping there was a more elegant way of doing this python-side. Unfortunately the pgq schema is locked. Thanks for the suggestion
0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.