【问题标题】:How to get a proper formatted index in a pandas dataframe如何在 pandas 数据框中获取正确格式的索引
【发布时间】:2017-07-24 21:56:41
【问题描述】:

有这样的数据框:

>>> df = pd.DataFrame({'name': ['foo', 'foo', 'bar', 'bar'],
                   'colx': [1, 2, 3, 4],
                   'coly': [5, 6, 7, 8]})
>>> df.set_index('name', inplace=True)
>>> df
      colx  coly
name            
foo      1     5
foo      2     6
bar      3     7
bar      4     8

如何获得正确格式的索引,例如:

      colx  coly
name            
foo      1     5
         2     6
bar      3     7
         4     8

这样 pandas 就不会抱怨重复索引。

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    一个(众多)选项是添加一个新的索引级别:

    In [49]: df = df.set_index(df.groupby(level=0).cumcount().add(1) \
                                 .to_frame('num')['num'],
                               append=True)
    
    In [50]: df
    Out[50]:
              colx  coly
    name num
    foo  1       1     5
         2       2     6
    bar  1       3     7
         2       4     8
    

    更新:不要对 Pandas 在多重索引中显示重复项的方式感到困惑:

    如果我们选择多索引的name 级别的所有值,我们仍然会看到重复项:

    In [51]: df.index.get_level_values(0)
    Out[51]: Index(['foo', 'foo', 'bar', 'bar'], dtype='object', name='name')
    

    这正是 Pandas 在多索引中表示重复项的方式。我们可以关闭这个显示选项:

    In [53]: pd.options.display.multi_sparse = False
    
    In [54]: df
    Out[54]:
              colx  coly
    name num
    foo  1       1     5
    foo  2       2     6
    bar  1       3     7
    bar  2       4     8
    
    In [55]: pd.options.display.multi_sparse = True
    
    In [56]: df
    Out[56]:
              colx  coly
    name num
    foo  1       1     5
         2       2     6
    bar  1       3     7
         2       4     8
    

    PS 这个选项不会改变索引值,它只影响 multi-indices 的表示

    【讨论】:

    • 这行得通,但熊猫不应该有一种不那么复杂的方式来实现同样的目标吗?此外,它还创建了一个多索引。
    • @PedroA,你能再解释一下 - 你想达到什么目的?你打算如何使用索引?保留现有索引值是否重要?我们可以在索引值中添加一个数字,以便它们变为:['foo1','foo2','bar1','bar2', etc.] - 您可以选择吗?如您所见,可能有许多不同的解决方案,但我们需要知道您要实现什么目标......
    • 抱歉,我还在学习 pandas,但我认为生成的 DF 将只有 name 列的索引。您现在添加了一个新索引num。我相信这一定是它,但你能稍微扩展一下你的答案为什么会这样吗?
    猜你喜欢
    • 2016-10-15
    • 2020-01-26
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2019-09-10
    • 2020-09-05
    相关资源
    最近更新 更多