Python 如何从数据框的索引中获取行的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26640145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:47:38  来源:igfitidea点击:

How do I get the name of the rows from the index of a data frame?

pythonpandasdataframe

提问by linamnt

Consider a data frame with row names that aren't a column of their own per se, such as the following:

考虑一个数据框,其行名称本身不是一列,例如以下内容:

        X  Y
 Row 1  0  5
 Row 2  8  1
 Row 3  3  0

How would I extract the name of these rows as a list, if I have their index? For example, it would look something like:

如果我有它们的索引,我将如何将这些行的名称提取为列表?例如,它看起来像:

function_name(dataframe[indices])
> ['Row 1', 'Row 2']

采纳答案by Adam Hughes

df.index

df.index

  • outputs the row names as pandas Indexobject.
  • 将行名称输出为 pandasIndex对象。

list(df.index)

list(df.index)

  • casts to a list.
  • 强制转换为列表。

df.index['Row 2':'Row 5']

df.index['Row 2':'Row 5']

  • supports label slicing similar to columns.
  • 支持类似于列的标签切片。

回答by heyitschun

if you want to get the index values, you can simply do:

如果要获取索引值,只需执行以下操作:

dataframe.index

数据框索引

this will output a pandas.core.index

这将输出一个 pandas.core.index

回答by K Raphael

If you want to pull out only the index values for certain integer-based row-indices, you can do something like the following using the ilocmethod:

如果您只想提取某些基于整数的行索引的索引值,您可以使用该iloc方法执行以下操作:

In [28]: temp
Out[28]:
       index                 time  complete
row_0      2  2014-10-22 01:00:00         0
row_1      3  2014-10-23 14:00:00         0
row_2      4  2014-10-26 08:00:00         0
row_3      5  2014-10-26 10:00:00         0
row_4      6  2014-10-26 11:00:00         0

In [29]: temp.iloc[[0,1,4]].index
Out[29]: Index([u'row_0', u'row_1', u'row_4'], dtype='object')

In [30]: temp.iloc[[0,1,4]].index.tolist()
Out[30]: ['row_0', 'row_1', 'row_4']

回答by Alex Kushkuley

this seems to work fine :

这似乎工作正常:

dataframe.axes[0].tolist()