简体   繁体   中英

Pandas inverse of pivot table

I have a DataFrame (eg, df_p ) which has already converted into a pivot table:

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

How should I convert df_p back to df ?

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

(can't guarantee this works in every case, however)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM