Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Pandas inverse of pivot table

I have a DataFrame (e.g., 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...