python - 按名称获取DataFrame索引

标签 python pandas

如何通过名称从多索引 DataFrame 访问一个索引?

例如,我想使用字符串“year”从此数据帧访问“year”索引:

df.tail()

dayofyear  year
361        2015   -7.244481
362        2015   -7.245178
363        2015   -7.245608
364        2015   -7.245999
365        2015   -7.246563

我需要使用.reset_index吗?

最佳答案

您可以使用 get_level_values 查询多索引以获得特定级别的值。 :

In [163]:
df.index.get_level_values('year')

Out[163]:
Int64Index([2015, 2015, 2015, 2015, 2015], dtype='int64', name='year')

这接受序数位置或级别字符串值

关于python - 按名称获取DataFrame索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35059288/

相关文章:

python - Azure Functions Python 连接到 Azure SQL DB

python - Pandas 中的 groupby -Python

Python 线程优于简单的 while 循环或线程优化

python - 如何在 Python 中合并多个具有不同表列的 Excel 工作表?

python - 使用Python的组合方法

python - 在django模板中显示parent_model

python - 对 ModelForm 进行单元测试时出现错误

python - np.logic_or 与reduce 返回不同的结果

python - 使用pandas读取rpt文件

python-3.x - 为什么使用 sklearn 库随机生成的数据精度较低