Search code examples
pythonpandasmulti-index

pandas - add values into column with header into mutltiindex (header) based on variables


First, I created a pandas multi-index data frame (df). Second, I have variables and a data frame (df_TV). I like to add values from "df_TV" into "df" based on the variables "TV_Object", "TV_weight", "TV_room" and the index. Also, I like to add "TV" at the lowest level of the multi-index.

Creates the multi-index df:

header = pd.MultiIndex.from_product([
    ['Electrical Device', 'piece of furniture'],
    ['>10 Kilogramm','<10 Kilogramm'],        
    ['Kitchen', 'Living Room','Bathroom'],
    ], names=['Object','weight', 'room'])
df = pd.DataFrame(index=['a','b','c','d','e'], columns=header)
df

Create the variables and df_TV:

TV_Object = 'Electrical Device'
TV_weight = '>10 Kilogramm'
TV_room = 'Living Room'

df_TV = pd.DataFrame(np.random.randn(5,1), index=['a','b','c','d','e'], columns=['TV'])
df_TV  

I obtain, that the values will be added by index a,b,c, etc. and a new multi-index-header "TV" is under "Living Room" followed by the values. Thanks for ideas/solutions and your time!


Solution

  • Here it is:

    Solution

    df[(TV_Object, TV_weight, TV_room)] = df_TV['TV']
    

    Output

    print(df.to_string())
    
    Object Electrical Device                                                         piece of furniture                                                        
    weight     >10 Kilogramm                      <10 Kilogramm                           >10 Kilogramm                      <10 Kilogramm                     
    room             Kitchen Living Room Bathroom       Kitchen Living Room Bathroom            Kitchen Living Room Bathroom       Kitchen Living Room Bathroom
    a                    NaN    0.495962      NaN           NaN         NaN      NaN                NaN         NaN      NaN           NaN         NaN      NaN
    b                    NaN   -1.040295      NaN           NaN         NaN      NaN                NaN         NaN      NaN           NaN         NaN      NaN
    c                    NaN   -0.653766      NaN           NaN         NaN      NaN                NaN         NaN      NaN           NaN         NaN      NaN
    d                    NaN   -0.152420      NaN           NaN         NaN      NaN                NaN         NaN      NaN           NaN         NaN      NaN
    e                    NaN    0.950787      NaN           NaN         NaN      NaN                NaN         NaN      NaN           NaN         NaN      NaN