【问题标题】:How do I get the name of the rows from the index of a data frame?如何从数据框的索引中获取行的名称?
【发布时间】:2014-12-25 17:39:07
【问题描述】:

考虑一个数据框,其行名本身不是一列,如下所示:

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

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

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

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    df.index

    • 将行名称输出为 pandas Index 对象。

    list(df.index)

    • 投射到列表中。

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

    • 支持类似于列的标签切片。

    【讨论】:

      【解决方案2】:

      这似乎工作正常:

      dataframe.axes[0].tolist()
      

      【讨论】:

        【解决方案3】:

        如果您只想提取某些基于整数的行索引的索引值,您可以使用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']
        

        【讨论】:

          【解决方案4】:

          如果你想获取索引值,你可以这样做:

          dataframe.index

          这将输出 pandas.core.index

          【讨论】:

            猜你喜欢
            • 2012-07-05
            • 2017-05-31
            • 2013-08-08
            • 1970-01-01
            • 1970-01-01
            • 2014-01-06
            • 1970-01-01
            • 2014-04-27
            • 1970-01-01
            相关资源
            最近更新 更多