我正在使用presto sql并被卡住。
我想将列转换为新行并保存值。
例如:
之前
NAME COMDEDY HORROR ROMANCE
brian 10 20 14
tom 20 10 11
之后
NAME GANRE RATING
brian comedy 10
brian horror 20
brian romance 14
tom comedy 20
tom horror 10
tom romance 11
如果我不能使用prestodb做到这一点,至少需要使用python pandas来做到这一点
谢谢!
答案 0 :(得分:4)
您可以使用presto sql来做到这一点:
SELECT t1.name, t2.genre, t2.rating
FROM table t1
CROSS JOIN unnest (
array['comedy', 'horror', 'romance'],
array[comedy, horror, romance]
) t2 (genre, rating)
答案 1 :(得分:0)
您可以尝试以下方法:
df = pd.melt(df, id_vars=["NAME"], var_name=['COMDEDY,HORROR,ROMANCE'])
df.rename(columns={'value':'RATING', 'COMDEDY,HORROR,ROMANCE':'GANRE'}, inplace=True)
df.sort_values("NAME", inplace=True)
print(df)