【问题标题】:Removing or merging multiindex columns in pandas dataframe without losing data删除或合并熊猫数据框中的多索引列而不丢失数据
【发布时间】:2018-12-23 05:01:18
【问题描述】:

我有一个由 pdblp 模块为 python 创建的数据框。 df 包含以日期为索引的价格数据,以及看起来像多索引/两层列(ticker 和'PX_LAST')的东西。为了以更简单的方式处理数据,我想去掉子标题“PX_LAST”(我不需要它,它会与我单独执行的一些查找功能混淆)。

这是数据框的外观:

df_px_orig.columns

Out[60]: 
MultiIndex(levels=[['IKH16 Comdty', 'IKM16 Comdty', 'IKU16 Comdty', 'RXH16 Comdty', 'RXM16 Comdty', 'RXU16 Comdty'], ['PX_LAST']],
           labels=[[3, 4, 5, 0, 1, 2], [0, 0, 0, 0, 0, 0]],
           names=['ticker', 'field'])

df_px_orig.head()

Out[41]: 
ticker     RXH16 Comdty RXM16 Comdty RXU16 Comdty IKH16 Comdty IKM16 Comdty  \
field           PX_LAST      PX_LAST      PX_LAST      PX_LAST      PX_LAST   
date                                                                          
2016-01-04       158.79       156.26       155.15       138.28       136.76   
2016-01-05       159.05       156.52       155.42       138.73       137.21   
2016-01-06       159.69       157.15       156.04       139.01       137.49   
2016-01-07       159.18       156.62       155.53       138.18       136.66   
2016-01-08       159.66       157.11       155.98       138.53       137.01   

ticker     IKU16 Comdty  
field           PX_LAST  
date                     
2016-01-04       136.76  
2016-01-05       137.21  
2016-01-06       137.49  
2016-01-07       136.66  
2016-01-08       137.01  

我遇到的问题是建议的方法:

这里使用 columns.map():{Pandas: combining header rows of a multiIndex DataFrame}

这里使用 columns.droplevel():{Delete second row of header in PANDAS}

这两者的结果是一样的——貌似把所有的数据都去掉了,我剩下的新对象只是一个索引:

dftest = df_px_orig.columns.droplevel(1)

dftest
Out[55]: 
Index(['RXH16 Comdty', 'RXM16 Comdty', 'RXU16 Comdty', 'IKH16 Comdty',
       'IKM16 Comdty', 'IKU16 Comdty'],
      dtype='object', name='ticker')

dftest.head()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-56-f54d042ff4d9> in <module>()
----> 1 dftest.head()

AttributeError: 'Index' object has no attribute 'head'

也许我完全误解了这个数据框的结构,应该使用其他方法,非常感谢帮助。需要明确的是,我的目标是简单地摆脱“PX_LAST”级别并保持其他所有内容相同。

非常感谢

编辑:从用于构建数据框的插件源添加一些代码:{https://github.com/matthewgilbert/pdblp/blob/master/pdblp/pdblp.py}

 def bdh(self, tickers, flds, start_date, end_date, elms=None,
            ovrds=None, longdata=False):
        """
        Get tickers and fields, return pandas DataFrame with columns as
        MultiIndex with levels "ticker" and "field" and indexed by "date".
        If long data is requested return DataFrame with columns
        ["date", "ticker", "field", "value"].
        Parameters
        ----------
        tickers: {list, string}
            String or list of strings corresponding to tickers
        flds: {list, string}
            String or list of strings corresponding to FLDS
        start_date: string
            String in format YYYYmmdd
        end_date: string
            String in format YYYYmmdd
        elms: list of tuples
            List of tuples where each tuple corresponds to the other elements
            to be set, e.g. [("periodicityAdjustment", "ACTUAL")].
            Refer to the HistoricalDataRequest section in the
            'Services & schemas reference guide' for more info on these values
        ovrds: list of tuples
            List of tuples where each tuple corresponds to the override
            field and value
        longdata: boolean
            Whether data should be returned in long data format or pivoted

【问题讨论】:

  • 你能给我们一些从头开始构建部分数据框的代码吗?有关提示,请参阅this answer
  • 嗨!数据框是使用'df_px_orig = con.bdh(contract_list, ['PX_LAST'], '20160101', '20160113') 创建的,其中contract_list = ['RXH16 Comdty', 'RXM16 Comdty' ... etc for all contract tickers]。进行构建的插件是pdblp,并且没有那么多文档。 {github.com/matthewgilbert/pdblp}。我会看看我是否可以在源代码中找到一些东西,但我有点 n00b,所以不太确定去哪里找。

标签: python pandas dataframe multi-index


【解决方案1】:

请尝试使用:

df.reset_index(level = <level of the index you wish to drop> , drop = True, inplace = True)

它可以满足您的要求,即重置索引级别并保持数据不变。

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2018-02-02
    • 2014-11-05
    • 1970-01-01
    • 2021-03-25
    • 2020-10-31
    相关资源
    最近更新 更多