1

For analysis it is sometimes better to access columns of a select-result instead of rows. Let's say we want to plot a voltage trace of a specific recording point (rp) and the data is stored in a table *recordings*like this

__________________________________
|rp_key  | time       | value_mV |
----------------------------------
|  1     |    1       |    -65   |
----------------------------------
|  1     |    2       |    -64.4 |
----------------------------------
|  1     |    3       |    -65.3 |
----------------------------------
|  2     |    1       |    -67.9 |
----------------------------------
|  2     |    2       |    -68.0 |
----------------------------------

Now I would like to plot like this:

import sqlalchemy as sa
import matplotlib.pyplot as plt
# ...
res = session.query(Recording).filter_by(rp_key=1).all()
# HERE: elegant sqlalchemy-way of accessing the columns of the result
plt.plot(time, value_mV)

What would you suggest?

Philipp der Rautenberg
  • 2,212
  • 3
  • 25
  • 39

1 Answers1

2

SQLAlchemy allows to query for specified columns only. All you need is to transpose resulting matrix. Assuming Recording is a mapped class the code might look as following:

rows = session.query(Recording.time, Recording.value_mV).filter_by(rp_key=1).all()
time, value_mV = zip(*rows)
plt.plot(time, value_mV)
Community
  • 1
  • 1
Denis Otkidach
  • 32,032
  • 8
  • 79
  • 100