系列到DataFrame

时间:2017-09-24 15:58:48

标签: pandas

我的系列看起来像这样:

                     Adj Close
Date        minor   
2017-09-22  AFK      23.500000
            ASHR     29.530001
            ECH      49.259998
            EGPT     28.139999
            EIDO     26.950001

也就是说,对于几个ETF,我每天都有Adj Close。

我想将其转换为DataFrame sush as:

              AFK         ASHR       ECH
Date            
2017-09-22    23.500000   29.530001  49.259998 ...
2017-09-23    ...

我尝试过使用pivot():

h.pivot(index="Date", columns = "minor")  

但是我收到了一条错误消息。

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\Users\USUARIO\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2392             try:
-> 2393                 return self._engine.get_loc(key)
   2394             except KeyError:


KeyError: 'Date'

During handling of the above exception, another exception occurred:

 ...

KeyError: 'Date'

我做错了什么?

1 个答案:

答案 0 :(得分:2)

我认为您需要Series.unstack,请通过使用[]建立索引来选择该列以获取该系列:

df1 = df['Adj Close'].unstack()
print (df1)
minor        AFK       ASHR        ECH       EGPT       EIDO
Date                                                        
2017-09-22  23.5  29.530001  49.259998  28.139999  26.950001

如果要使用pivot,请先reset_indexMultiIndex创建列:

print (df.reset_index())
         Date minor  Adj Close
0  2017-09-22   AFK  23.500000
1  2017-09-22  ASHR  29.530001
2  2017-09-22   ECH  49.259998
3  2017-09-22  EGPT  28.139999
4  2017-09-22  EIDO  26.950001

df1 = df.reset_index().pivot(index='Date', columns='minor', values='Adj Close')
print (df1)
minor        AFK       ASHR        ECH       EGPT       EIDO
Date                                                        
2017-09-22  23.5  29.530001  49.259998  28.139999  26.950001