在熊猫中创建迭代的多索引和多列数据框

时间:2020-04-29 13:31:09

标签: python pandas dataframe multi-index

假设我要创建一个多索引和多列数据框:

                          X         Y
Planet Continent Country  A    B    C     D 
Earth     Europe England  0.3  0.5  0.6   0.8
          Europe Italy    0.1  0.2  0.4   1.2 
Mars      Tempe  Sirtys   3.2  4.5  2.3   4.2 

我想通过迭代收集数据帧的每一行来做到这一点,

row1 =  np.array(['Earth', 'Europe', 'England', 0.3, 0.5, 0.6, 0.8])
row2 =  np.array(['Earth', 'Europe', 'Italy', 0.1, 0.2, 0.4, 1.2])

我知道如何从行开始创建多列数据框,并且知道如何创建多索引数据框。但是如何创建两者呢? 谢谢

2 个答案:

答案 0 :(得分:2)

如果您从一个空的数据帧开始,使用multiindex索引和列进行定义(如您所知):

df = pd.DataFrame(index=pd.MultiIndex(levels=[[]]*3, 
                                      codes=[[]]*3, 
                                      names=['Planet','Continent','Country']), 
                 columns=pd.MultiIndex.from_tuples([('X','A'), ('X','B'),
                                                    ('Y','C'), ('Y', 'D')],))

然后,您可以像这样添加每行:

df.loc[tuple(row1[:3]), :]= row1[3:]
print (df)
                            X         Y     
                            A    B    C    D
Planet Continent Country                    
Earth  Europe    England  0.3  0.5  0.6  0.8

并在之后:

df.loc[tuple(row2[:3]), :]= row2[3:]
print (df)
                            X         Y     
                            A    B    C    D
Planet Continent Country                    
Earth  Europe    England  0.3  0.5  0.6  0.8
                 Italy    0.1  0.2  0.4  1.2

但是如果您一次有很多行可用,@Yo_Chris的答案将更加简单

答案 1 :(得分:2)

row1 =  np.array(['Earth', 'Europe', 'England', 0.3, 0.5, 0.6, 0.8])
row2 =  np.array(['Earth', 'Europe', 'Italy', 0.1, 0.2, 0.4, 1.2])
# create a data frame and set index
df = pd.DataFrame([row1, row2]).set_index([0,1,2])
# set the index names
df.index.names = ['Planet', 'Continent', 'Country']
# create a multi-index and assign to columns
df.columns = pd.MultiIndex.from_tuples([('X', 'A'), ('X', 'B'), ('Y', 'C'), ('Y', 'D')])

                            X         Y     
                            A    B    C    D
Planet Continent Country                    
Earth  Europe    England  0.3  0.5  0.6  0.8
                 Italy    0.1  0.2  0.4  1.2