在 Pandas 中创建迭代多索引和多列数据框 [英] create iteratively multi index and multi columns dataframe in pandas

查看:65
本文介绍了在 Pandas 中创建迭代多索引和多列数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say that I want to create a multi index and multi column dataframe:

                          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 

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

I want to do that by iteratively collecting each single row of the dataframe,

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

我知道如何从行开始创建多列数据框,我知道如何创建多索引数据框.但是我怎样才能创建两者呢?谢谢

I know how, starting with rows, I can create a multi-column dataframe, and I know how I can create a multi-index one. But how can I create both? Thanks

推荐答案

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

这篇关于在 Pandas 中创建迭代多索引和多列数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆