首页 文章

Pandas索引列 Headers 或名称

提问于
浏览
156

如何在python pandas中获取索引列名?这是一个示例数据帧:

Column 1
Index Title          
Apples              1
Oranges             2
Puppies             3
Ducks               4

我想要做的是获取/设置数据帧索引 Headers . 这是我试过的:

import pandas as pd
data = {'Column 1'     : [1., 2., 3., 4.],
        'Index Title'  : ["Apples", "Oranges", "Puppies", "Ducks"]}
df = pd.DataFrame(data)
df.index = df["Index Title"]
del df["Index Title"]
print df

有人知道怎么做吗?

7 回答

  • 0

    您可以通过 name 属性获取/设置索引

    In [7]: df.index.name
    Out[7]: 'Index Title'
    
    In [8]: df.index.name = 'foo'
    
    In [9]: df.index.name
    Out[9]: 'foo'
    
    In [10]: df
    Out[10]: 
             Column 1
    foo              
    Apples          1
    Oranges         2
    Puppies         3
    Ducks           4
    
  • 12

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

    print df
                 Column 1
    Index Title          
    Apples            1.0
    Oranges           2.0
    Puppies           3.0
    Ducks             4.0
    

    新功能在方法链中运行良好 .

    print df.rename_axis('foo')
             Column 1
    foo              
    Apples        1.0
    Oranges       2.0
    Puppies       3.0
    Ducks         4.0
    

    您还可以使用参数 axis 重命名列名:

    print df
    Col Name     Column 1
    Index Title          
    Apples            1.0
    Oranges           2.0
    Puppies           3.0
    Ducks             4.0
    
    print df.rename_axis('foo').rename_axis("bar", axis="columns")
    bar      Column 1
    foo              
    Apples        1.0
    Oranges       2.0
    Puppies       3.0
    Ducks         4.0
    
    print df.rename_axis('foo').rename_axis("bar", axis=1)
    bar      Column 1
    foo              
    Apples        1.0
    Oranges       2.0
    Puppies       3.0
    Ducks         4.0
    
  • 6

    df.index.name 应该做的伎俩 .

    Python有一个 dir 函数,让你查询对象属性 . dir(df.index) 在这里很有帮助 .

  • 44

    使用 df.index.rename('foo', inplace=True) 设置索引名称 .

    似乎这个api自pandas 0.13起可用 .

  • 11

    如果您不想创建新行但只是将其放在空单元格中,那么使用:

    df.columns.name = 'foo'
    

    否则使用:

    df.index.name = 'foo'
    
  • 203

    df.columns.values 也给我们列名

  • 26

    根据kaggle pandas tour,以下作品:

    df.rename_axis('new_name', axis='rows')

    reviews.index.name # now returns 'wines'

相关问题