Home > Mobile >  Assigning values to a multi-index pandas data frame
Assigning values to a multi-index pandas data frame

Time:09-29

This is my multiindex dataframe.

import pandas as pd
import numpy as np
arrays=[['A','A','A','A','B','B','B','B',
          'C','C','C','C','D','D','D','D','E','E','E','E'],[1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]]
hier_index=list(zip(*arrays))
#hier_index=pd.MultiIndex.from_tuples(hier_index)
hier_index
index=pd.MultiIndex.from_tuples(hier_index,names=["Camera","position"])
df1=pd.DataFrame(np.zeros([3,20]),index=["x","y","z"], columns=index)

I also have two for loops:

for i in range(0,20):
    x=[]
    for j in range(0,4):
        x_r= an equaton
        x.append(x_r)
    print(x)

the output of four loops is 5 lists with 4 elements each list is associated with A, B,C,D,E respectively. e.g. [0,0.1,0.2,0.3] , [0,0.4,0.5,0.6], and so on. I want to assign elements of each list to 1,2,3,4 sub columns for all columns A,B,C,D,E. I don't know how to do that.

CodePudding user response:

I assume that you will need both i and j in the for loops for something so, I did not remove them. You can use enumerate to iterate through the top level index (e.g. A, B, C,...) and still keep the numeric index i. With this you can simply assign x to a slice of your data frame using loc. The loop below assigns your x (created with the equation 20*I j) to the slice, df1.loc['x', (c,1):(c,4)] = x, which specifies the row 'x' and the columns (c,1):(c,4) where c is one of your labels (e.g. A,B,C,...).

for i,c in enumerate(df1.columns.levels[0]):
    x=[]
    for j in range(0,4):
        x_r= 20*i j
        x.append(x_r)
    df1.loc['x', (c,1):(c,4)] = x
    print(x)
  • Related