【问题标题】:Remove index name in pandas删除熊猫中的索引名称
【发布时间】:2015-06-28 05:18:23
【问题描述】:

我有一个像这样的数据框:

In [10]: df
Out[10]: 
         Column 1
foo              
Apples          1
Oranges         2
Puppies         3
Ducks           4

如何从该数据框中删除 index name foo? 想要的输出是这样的:

In [10]: df
Out[10]: 
         Column 1             
Apples          1
Oranges         2
Puppies         3
Ducks           4

【问题讨论】:

  • df.index.name = None

标签: python pandas indexing rowname


【解决方案1】:

或者,您可以将None 分配给index.name 属性:

>>> df.index.name = None
>>> print(df)
         Column 1    
Apples          1
Oranges         2
Puppies         3
Ducks           4

【讨论】:

  • 使用 Pandas 1.3.3 完美查找 Python 3.9.7
【解决方案2】:

使用del df.index.name

In [16]: df
Out[16]:
         Column 1
foo
Apples          1
Oranges         2
Puppies         3
Ducks           4

In [17]: del df.index.name

In [18]: df
Out[18]:
         Column 1
Apples          1
Oranges         2
Puppies         3
Ducks           4

【讨论】:

  • 对于pandas 1.0.3 版,这似乎不再起作用。它因“AttributeError:无法删除属性”而失败。
  • @billjoie 你知道如何在 pandas 1.0.3 中解决这个问题吗? , 因为del df.index.name 不起作用
  • @mrn,@EdChum conctionne très bien 解决方案:df.index.name = None
  • @billjoie 祝福你的心。有一段时间了。该 del df.index.name 不适用于更高版本的熊猫。
  • Python 3.9.7 和 Pandas 1.3.3:AttributeError:无法删除属性
【解决方案3】:

我花了很长时间才找到真正适合我的答案。见下文。

df = df.rename_axis(None, axis=1)

我确信其中一些其他答案对其他人有用,但它们绝对不适合我:(

【讨论】:

  • 这是唯一对我有用的答案;使用 rename_axis() 并添加 axis=1
  • 确认这是唯一适合我的答案!
【解决方案4】:

0.18.0 版本开始,您可以使用rename_axis

print df
         Column 1
foo              
Apples          1
Oranges         2
Puppies         3
Ducks           4

print df.index.name
foo


print df.rename_axis(None)
         Column 1
Apples          1
Oranges         2
Puppies         3
Ducks           4

print df.rename_axis(None).index.name
None

# To modify the DataFrame itself:
df.rename_axis(None, inplace=True)
print df.index.name
None

【讨论】:

    【解决方案5】:

    对于您的情况,只需使用以下代码。在 pandas 1.0.1 上测试。

    df = df.rename_axis(index=None)
    

    【讨论】:

      【解决方案6】:

      简单的改变——就地做:

      df_degree.rename_axis(None, axis=1, inplace=True)
      

      【讨论】:

        猜你喜欢
        • 2020-01-04
        • 1970-01-01
        • 2018-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多