首页 > 解决方案 > 如何使日期列对 postgres 而不是 Python 中的数据探索更具吸引力?

问题描述

我有一张使用 Plotly-Dash 制作的股市数据图表。我为日期绘制 x,为价格绘制 y。当将 x 数据绘制为日期时,标签对于数据探索来说总是很奇怪。

例如: 在此处输入图像描述

如您所见,x 轴是一年中一月和七月的一系列月份。这自然是自动生成的,不适合用户体验。如果有 2015 年第一季度、2015 年第二季度或 2016 年冬季、2016 年夏季等会更好……

在 Python 中,我可以通过类似这样的编辑数据框来做到这一点:

for column in lst:
    column.loc[column["month_int"] == 1, "month"] = "January"
    column.loc[column["month_int"] == 2, "month"] = "February"
    column.loc[column["month_int"] == 3, "month"] = "March"
    column.loc[column["month_int"] == 4, "month"] = "April"
    column.loc[column["month_int"] == 5, "month"] = "May"
    column.loc[column["month_int"] == 6, "month"] = "June"
    column.loc[column["month_int"] == 7, "month"] = "July"
    column.loc[column["month_int"] == 8, "month"] = "August"
    column.loc[column["month_int"] == 9, "month"] = "September"
    column.loc[column["month_int"] == 10, "month"] = "October"
    column.loc[column["month_int"] == 11, "month"] = "November"
    column.loc[column["month_int"] == 12, "month"] = "December"
    
# Or like this     

for column in lst2:
    column.loc[(column['month_int'] > 2) & (column['month_int'] <= 5), 'Season'] = 'Spring'
    column.loc[(column['month_int'] > 5) & (column['month_int'] <= 8), 'Season'] = 'Summer'
    column.loc[(column['month_int'] > 8) & (column['month_int'] <= 11), 'Season'] = 'Autumn'
    column.loc[column['month_int'] <= 2, 'Season'] = 'Winter'
    column.loc[column['month_int'] == 12, 'Season'] = 'Winter

除了 Postgres 之外,还有什么等价的?我正在尝试学习更多 SQL 技巧并替换不必要的 python 代码。供参考,这是我的查询

SELECT symbol, date, adj_close 
FROM api.security_price 
WHERE security_price.symbol IN %s AND date > (SELECT MAX(date) FROM api.security_price) - interval '5 years' 
ORDER by date;

标签: pythonpostgresql

解决方案


要获取月份,您可以使用TO_CHARpostgres 中的函数。

select symbol, date, to_char(date, 'Month') as month, adj_close from api.security_price 
WHERE security_price.symbol IN %s AND date > (SELECT MAX(date) FROM api.security_price) - interval '5 years' 
ORDER by date;

参考:https ://www.postgresql.org/docs/current/functions-formatting.html

同样,您也可以针对特殊情况定义自己的 sql 查询函数。参考:https ://www.postgresql.org/docs/current/xfunc-sql.html 。

对于季节,另一种简单的方法是使用另一列包含 month_int 到季节的映射,并在输出数据上与该表进行左连接。


推荐阅读