gpt4 book ai didi

python - 生成一个摘要 ("pivot"?) 表

转载 作者:IT王子 更新时间:2023-10-29 06:27:02 24 4
gpt4 key购买 nike

我想要一种汇总数据库表的方法,以便将共享公共(public) ID 的行汇总到一行输出中。

我的工具是 SQLite 和 Python 2.x。

例如,给出下表我本地超市的水果价格...

+--------------------+--------------------+--------------------+
|Fruit |Shop |Price |
+--------------------+--------------------+--------------------+
|Apple |Coles |$1.50 |
|Apple |Woolworths |$1.60 |
|Apple |IGA |$1.70 |
|Banana |Coles |$0.50 |
|Banana |Woolworths |$0.60 |
|Banana |IGA |$0.70 |
|Cherry |Coles |$5.00 |
|Date |Coles |$2.00 |
|Date |Woolworths |$2.10 |
|Elderberry |IGA |$10.00 |
+--------------------+--------------------+--------------------+

...我想生成一个汇总表,显示每个超市每种水果的价格。空格应由 NULL 填充。

+----------+----------+----------+----------+
|Fruit |Coles |Woolworths|IGA |
+----------+----------+----------+----------+
|Apple |$1.50 |$1.60 |$1.70 |
|Banana |$0.50 |$0.60 |$0.70 |
|Cherry |NULL |$5.00 |NULL |
|Date |$2.00 |$2.10 |NULL |
|Elderberry|NULL |NULL |$10.00 |
+----------+----------+----------+----------+

我相信文献称其为“数据透视表”或“数据透视查询”,但显然 SQLite doesn't support PIVOT. (该问题中的解决方案使用硬编码的 LEFT JOIN。这对我来说并没有真正的吸引力,因为我事先不知道“列”名称。)

现在我通过在 Python 中遍历整个表并累积 dictsdict 来完成此操作,这有点笨拙。我愿意接受更好的解决方案,无论是在 Python 还是 SQLite 中,它们都会以表格形式提供数据。

最佳答案

pandas 包可以很好地处理这个问题。

>>> import pandas
>>> df=pandas.DataFrame(data, columns=['Fruit', 'Shop', 'Price'])
>>> df.pivot(index='Fruit', columns='Shop', values='Price')
Shop Coles IGA Woolworths
Fruit
Apple 1.5 1.7 1.6
Banana 0.5 0.7 0.6
Cherry 5.0 NaN NaN
Date 2.0 NaN 2.1
Elderberry NaN 10.0 NaN

文档: http://pandas.pydata.org/pandas-docs/stable/reshaping.html

一些用于学习 pandas 的 IPython 笔记本: https://bitbucket.org/hrojas/learn-pandas

希望对您有所帮助。
问候
帕特里克布罗克曼

关于python - 生成一个摘要 ("pivot"?) 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11428271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com