熊猫:如何“透视”数据透视表?

时间:2018-01-11 22:41:27

标签: python pandas

我有一个DataFrame(例如,df_p)已经转换为数据透视表:

import pandas as pd
df = pd.DataFrame({'start_year':[2000, 2001, 2002],
                  'end_year':[2010, 2011, 2012],
                  'price':[1.0, 2.0, 3.0]})

#    end_year  price  start_year
# 0      2010    1.0        2000
# 1      2011    2.0        2001
# 2      2012    3.0        2002

df_p = df.pivot('start_year', 'end_year', 'price')

# end_year    2010  2011  2012
# start_year                  
# 2000         1.0   NaN   NaN
# 2001         NaN   2.0   NaN
# 2002         NaN   NaN   3.0

如何将df_p转换回df

1 个答案:

答案 0 :(得分:3)

stack

df_p.stack().reset_index(name='price')

   start_year  end_year  price
0        2000      2010    1.0
1        2001      2011    2.0
2        2002      2012    3.0

melt + dropna

(但不能保证在每种情况下都适用)

df_p.reset_index().melt('start_year', value_name='price').dropna()

   start_year end_year  price
0        2000     2010    1.0
4        2001     2011    2.0
8        2002     2012    3.0