Search code examples
pythonpython-3.xdataframemulti-index

How can I name the second row of the first column in a multi-index data frame? It is blank now


I'm working with a mulit-index data frame. This is my first time ever dealing with this kind of thing. It's a bit unorthodox, but I know I really need two headers in this scenario. So, here's the first few columns of the DF.

df_append.columns.values

Result:

array([('IDRSSD', 'Unnamed: 0_level_1'),
       ('RCFD3531', 'TRDG ASSETS-US TREAS SECS IN DOM OFF'),
       ('RCFD3532', 'TRDG ASSETS-US GOV AGC CORP OBLGS'),
       ('RCFD3533', 'TRDG ASSETS-SECS ISSD BY ST  POL SUB'),
       ('RCFD3534', 'TRDG ASSETS-MBS-PASS-THRU-FNMA,FHLMC'),
       ('RCFD3535', 'TRDG ASSETS-MBS-CMOS&REMICS-FNMA,ETC'),
       ('RCFD3536', 'TRDG ASSETS-MBS-ALL OTHER'),

I want to assign a name to this thing:

'Unnamed: 0_level_1'

It's blank now, and it's causing some problems for me. So, I tried this:

df_append.columns.values[:1] = ['IDRSSD','IDRSSD_ID']

That seems to create a list inside of the array. I don't think that's going to work. I think the thing that I need to do is to name this thing: 'Unnamed: 0_level_1' to be this thing: 'IDRSSD_ID'

Or, if I am wrong, and this needs to be handled differently, please let me know. Thanks.


Solution

  • Get the level, modify it, set the index on the DataFrame

    df = pd.DataFrame([[1,2,3], [10,20,30], [100,200,300]])
    df.columns = pd.MultiIndex.from_tuples((("a", "b"), ("a", "c"), ("d", "f")))
    

    This changes the name for level 1 of the last column.

    >>> df
         a         d
         b    c    f
    0    1    2    3
    1   10   20   30
    2  100  200  300
    >>> df.columns.values
    array([('a', 'b'), ('a', 'c'), ('d', 'f')], dtype=object)
    >>> level1 = df.columns.get_level_values(1)
    >>> level1.values[-1] = '999'
    >>> level1
    Index(['b', 'c', '999'], dtype='object')
    >>> df.columns.set_levels(level1.values,level=1,inplace=True)
    >>> df
         a         d
         b    c  999
    0    1    2    3
    1   10   20   30
    2  100  200  300
    >>>