将列转换为pandas中的行

时间:2015-01-06 02:32:54

标签: python-2.7 pandas data-analysis

我有一个每年都有新生婴儿名字的数据框。

"name","1998","1999","2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013"
"Aicha",0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0
"Aida",15,20,16,0,10,0,10,14,13,11,12,11,13,14,13,18
"Aina",0,0,0,0,0,0,16,12,15,13,12,14,10,11,0,12
"Aisha",14,0,10,12,15,13,28,33,26,26,52,44,43,54,68,80
"Ajla",15,10,0,0,22,18,28,27,26,26,19,16,19,22,17,27
"Alba",0,0,14,14,22,14,17,19,23,15,28,32,25,33,33,33

我想在折线图中绘制它,其中每一行是不同的名称,x轴是年份。为了做到这一点,我想我需要将数据重塑为这样的东西:

"name","year","value"
"Aicha","1998",0
"Aicha","1999",0
"Aicha","2000",0
...

如何以这种方式重塑数据?我试过pivot_table,但我似乎无法让它发挥作用。

1 个答案:

答案 0 :(得分:1)

您可以使用pd.melt

>>> df_melted = pd.melt(df, id_vars="name", var_name="year")
>>> df_melted.head()
    name  year  value
0  Aicha  1998      0
1   Aida  1998     15
2   Aina  1998      0
3  Aisha  1998     14
4   Ajla  1998     15

然后使用

排序
>>> df_melted = df_melted.sort("name")

如果你喜欢。