python - Pandas 索引列标题或名称

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

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

我要做的是获取/设置数据框索引标题。这是我尝试过的:

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

有人知道怎么做吗?

最佳答案

您可以通过它的 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

https://stackoverflow.com/questions/18022845/

相关文章:

python - 为什么很多例子在 Matplotlib/pyplot/python 中使用 `fi

python - 如何提高我的爪子检测能力?

linux - 如何将密码传递给scp?

linux - 我在哪里可以设置 crontab 将使用的环境变量?

linux - 突出显示类似于 grep 的文本,但不过滤掉文本

linux - 如何找出给定用户的组?

linux - 在 Ubuntu 中创建目录的符号链接(symbolic link)

python - 将 matplotlib 图例移到轴外使其被图形框截断

python - 初始化 dict : curly brace literals {} or the

python - 删除具有重复索引的 pandas 行