在pandas中反复创建多索引和多列数据框架。

问题描述 投票:0回答:2

比方说,我想创建一个多索引和多列的数据框。

                          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])

我知道如何从行开始创建一个多列数据框,也知道如何创建一个多索引数据框。但我如何才能同时创建这两种数据框架呢?

python pandas dataframe multi-index
2个回答
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

2
投票

如果你从一个空的数据框架开始定义多索引和多列(根据你所知)。

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 会更容易

© www.soinside.com 2019 - 2024. All rights reserved.