本文介绍了枢纽分析表的 pandas 倒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我应该如何将df_p转换回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

(但是,不能保证在每种情况下都能奏效)


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

这篇关于枢纽分析表的 pandas 倒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 23:06