Pandas: Change a specific column name in dataframe having multilevel columns

后端 未结 3 1577
别那么骄傲
别那么骄傲 2021-02-14 02:05

I want to find the way change name of specific column in a multilevel dataframe.

With this data:

data = {
    (\'A\', \'1\', \'I\'): [1, 2, 3, 4, 5], 
           


        
3条回答
  •  半阙折子戏
    2021-02-14 02:30

    I came across this question as I was myself trying to find the solution for renaming the column names in a data frame with multiple levels. I tried the solution provided by @Dark Matter since it appeared to be very simple solution:

    dataDF.columns.levels = [[u'Z', u'B', u'C', u'D', u'E'], [u'100', u'2', u'3', u'4', u'5'], [u'Z', u'II', u'III']]
    

    But an error message was displayed:

    C:\anaconda3\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: setting `levels` directly is deprecated. Use set_levels instead
      """Entry point for launching an IPython kernel.
    

    It appears that it worked but does not work anymore. So I used:

    dataDF.columns.set_levels([['Z', 'B', 'C', 'D', 'E'],
                               ['100', '2', '3', '4', '5'],
                               ['Z', 'II', 'III']],
                              [0, 1, 2], inplace=True)
    

    Result: dataDF

    Z   B   C   D   E
    100 2   3   4   5
    Z   II  Z   II  III
    0   1   1   1   1   1
    1   2   2   2   2   2
    2   3   3   3   3   3
    3   4   4   4   4   4
    4   5   5   5   5   5
    

提交回复
热议问题