【问题标题】:create iteratively multi index and multi columns dataframe in pandas在 pandas 中迭代地创建多索引和多列数据框
【发布时间】:2020-08-13 14:41:33
【问题描述】:

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

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

我知道如何从行开始创建一个多列数据框,并且我知道如何创建一个多索引数据框。但是我怎样才能同时创建呢? 谢谢

【问题讨论】:

  • df.reset_index().to_numpy() ?
  • 如何开始?您是否已经在空数据框中拥有多索引索引和列?
  • 我认为 OP 想朝另一个方向发展。
  • 老实说,我可以以任何方式开始。重要的是,在某些时候我有这些行,我需要从中构建一个数据框,使用第一个 x 元素作为索引,另一个作为多列方式的值。也是的,我想从 numpy 转到 pandas :) 编辑:Ben,如果我理解你的问题,我有列名和多索引名称,而不是所有可能的索引。
  • 这还取决于您希望/需要如何创建数据框。您需要逐一更新行吗?或者您是否拥有所有行并想一次创建数据框?

标签: python pandas dataframe multi-index


【解决方案1】:

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

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

【讨论】:

  • 我选择了另一个,因为它更符合我的代码结构。不过还是谢谢!
【解决方案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

【讨论】:

  • 两个答案都很好,但这完全符合我的代码设计方式。谢谢!
猜你喜欢
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 2018-12-09
  • 2019-08-15
  • 2021-05-07
  • 2016-06-16
  • 2023-03-23
相关资源
最近更新 更多