Is there an elegant way to access table "columns" instead of rows with sqlalchemy?
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 | -6开发者_StackOverflow5 |
----------------------------------
| 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?
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)
精彩评论