将来自数据库查询的数据制成表格

发布于 2025-01-18 07:42:30 字数 422 浏览 3 评论 0原文

我觉得我要么没有寻找正确的术语,要么没有完全理解 Python 中数据“构造”方式与 SAS 或 SQL 相比的差异。

我已将 PyCharm Pro 连接到 Impala 数据库。我可以查询一个表,它以以下格式返回:

('福特'、'福克斯 2dr'、'column3data'、'column4data'、'etc')

我现在限制我的 SQL 查询,只获取前两列,然后将其打印到表格中。问题是,制表所做的就是将整行放入一个单元格中。

print(tabulate([records], headers=["make", "model"]))

我可以明白为什么如果我只打印 [records],因为它只是一个长字符串,但是如何制表以正确处理数据并将记录拆分到各自的列中?

I feel I'm either not searching for the correct terms or I'm not fully understanding the difference in how data is 'constructed' in Python compared to say, SAS or SQL.

I've connected PyCharm Pro to an Impala database. I'm able to query a table and it returns in format:

('Ford', 'Focus 2dr', 'column3data', 'column4data', 'etc')

I'm limiting my SQL query for now, just grabbing the first two columns, and I'm printing this into tabulate. The problem is, all tabulate is doing is putting that entire row into a single cell.

print(tabulate([records], headers=["make", "model"]))

I can see why if I just print the [records] as it's just a long string, but how do I get tabulate to treat the data properly and split the records into their respective columns?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

絕版丫頭 2025-01-25 07:42:30

您必须将该集合拆分为长度与列数匹配的块。

例如:

from tabulate import tabulate

your_sample_query = ('Ford', 'Focus 2dr', 'column3data', 'column4data', 'etc')
chop_it = [your_sample_query[i:i+2] for i in range(0, len(your_sample_query), 2)]
print(tabulate(chop_it, headers=["make", "model"], tablefmt="sql"))

这输出:

make         model
-----------  -----------
Ford         Focus 2dr
column3data  column4data
etc

You have to split that set into chunks of length that matches the number of columns.

For example:

from tabulate import tabulate

your_sample_query = ('Ford', 'Focus 2dr', 'column3data', 'column4data', 'etc')
chop_it = [your_sample_query[i:i+2] for i in range(0, len(your_sample_query), 2)]
print(tabulate(chop_it, headers=["make", "model"], tablefmt="sql"))

This outputs:

make         model
-----------  -----------
Ford         Focus 2dr
column3data  column4data
etc
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文