1

I am querying PostgreSQL using SQLAlchemy and wnat two select only two columns latitude and longitude and store it in numpy for further calculations. SO, I tried a query like this:

result = Places.query.filter_by(latitude, longitude)

But this query isn't working and giving a TYPE ERROR:

TypeError: filter_by() takes exactly 1 argument (2 given)

All i want to do is store the output of two columns and store it in numpy using something like :

np.array(..., dtype=float)

As I am new to both numpy and PostgreSQL, I am stuck in this.

Edit I have selected two columns using:

result = Places.query.with_entities(Places.latitude, Places.longitude).all()

Now, I just need to store them in numpy

2 Answers2

0

filter_by is roughly equivalent to WHERE in sql statements - it takes keyword arguments to filter results in a search, rather than select specific columns, e.g.:

Users.query().filter_by(first_name=bob, age=42)

(It defaults to and when joining keyword arguments, though can be wrapped in or_ to change this).

What you probably mean is to specify columns in your query, i.e.:

Places.query(Places.latitude, Places.longitude)
match
  • 10,388
  • 3
  • 23
  • 41
0

filter_by() is to select a specific set of rows based on criteria. For example, if your Places had a column called city and you wanted to get only the row belonging to a city named London, you would do something like:

session.query(Places).filter_by(city='London')

However, this will still fetch all the columns for London, not just longitude and latitude. In your case, it seems that you want to filter out columns, not rows. So, to get columns longitude and latitude for all the rows, you would need something like:

session.query(Places.latitude, Places.longitude)

This will return tuples. To store it as a list of numpy arrays you could try:

coordinates = []
for row in session.query(Places.latitude, Places.longitude):
   cooridnates.append(np.asarray(row))

Please refer to Object Relational Tutorial on simple examples of queries. It's hard to advice whether a list of numpy arrays is actually what you need without knowing your actual use case.

kovac
  • 4,945
  • 9
  • 47
  • 90
  • It says AttributeError: 'module' object has no attribute 'asarray' –  Feb 10 '18 at 10:45
  • Have you imported numpy? Something like `import numpy as np`. If `asarray` doesn't work, you can try `np.array(row)` instead. Make sure you have properly imported the numpy package. – kovac Feb 10 '18 at 10:48
  • It's unlikely that you are importing it correctly. Are you able to access any other functions in numpy elsewhere? There are similar questions on this: https://stackoverflow.com/questions/36530726/using-numpy-module-object-has-no-attribute-array – kovac Feb 10 '18 at 10:53
  • 1
    I am reinstalling numpy –  Feb 10 '18 at 10:55
  • 1
    Wait let me try. The issue was the name of my file itself was numpy.py. SO now my original installation is affected just give me some time –  Feb 10 '18 at 11:18