我们可以在 SQL(最好是 Postgresql)中模仿 pandas 函数pivot_table?
例如,假设我们有一个包含以下 3 列的表:
Name Day Value
John Sunday 6
John Monday 3
John Tuesday 2
Mary Sunday 6
Mary Monday 4
Mary Tuesday 7
Alex Tuesday 1
我想旋转表格,以便索引是名称,列是日期,单元格是值:
names Monday Sunday Tuesday
John 3 6 2
Mary 4 6 7
Alex null null 1
部分示例取自问题将 3 列数据帧转换为矩阵
据我所知,没有内置任何内容,但您可以使用它:
SELECT
Name AS names,
MAX(CASE WHEN Day = 'Monday' THEN Value END) AS Monday,
MAX(CASE WHEN Day = 'Sunday' THEN Value END) AS Sunday,
MAX(CASE WHEN Day = 'Tuesday' THEN Value END) AS Tuesday
FROM
names_table
GROUP BY
Name
ORDER BY
Name;