Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

关于SQL中一个表的转换问题

表结构如下:

date,a,b,c
0101,1,2,3
0202,4,5,6

要转换成:

date,col1,col2
0101,a,1
0202,a,4
0101,b,2
0202,b,5
0101,c,3
0202,c,6

想了很久,不知道该如何去写。使用Python的pandas和sql都可以,十分感谢!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

可以用pandas的melt方法

a = pd.DataFrame([[0101,1,2,3],[0202,4,5,6]],columns=['date','a','b','c'])
   date  a  b  c
0    65  1  2  3
1   130  4  5  6
pd.melt(a,id_vars=['date'],var_name='col1',value_name='col2')
   date col1  col2
0    65    a     1
1   130    a     4
2    65    b     2
3   130    b     5
4    65    c     3
5   130    c     6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...