【问题标题】:pivot table using python [duplicate]使用python的数据透视表[重复]
【发布时间】:2019-03-28 16:23:27
【问题描述】:

我有包含列的数据集

Country  
2001    
2002    
2003
...


import python as pd

df=pd.DataFrame({"country":['India','UK','France','US','Nepal'],'2001':[1,2,3,4,5],
               '2002':[1,2,3,4,5],'2003':[1,2,3,4,5],'2004':[1,2,3,4,5],
               '2005':[1,2,3,4,5],'2006':[1,2,3,4,5]})

我想用三列旋转这个表

Country    
Year    
Value

我应该如何为上面的输出扩展我的 python 代码?

【问题讨论】:

  • import python as pd?

标签: python pandas dataframe pivot-table


【解决方案1】:

你想要DataFrame.melt:

df.melt(id_vars='country', var_name='Year')

   country  Year  value
0    India  2001      1
1       UK  2001      2
2   France  2001      3
3       US  2001      4
4    Nepal  2001      5
5    India  2002      1
6       UK  2002      2
7   France  2002      3
8       US  2002      4
9    Nepal  2002      5
10   India  2003      1
...

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多