DataFrame对象中重新定义索引

DataFrame对象中重新定义索引

本文介绍了在Pandas DataFrame对象中重新定义索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重新索引熊猫DataFrame对象,

I am trying to re-index a pandas DataFrame object, like so,

From:
            a   b   c
        0   1   2   3
        1  10  11  12
        2  20  21  22

To :
           b   c
       1   2   3
      10  11  12
      20  21  22

我正在如下所示进行操作,并且得到了错误的答案.有关如何执行此操作的任何线索?

I am going about this as shown below and am getting the wrong answer. Any clues on how to do this?

>>> col = ['a','b','c']
>>> data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
>>> data
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22
>>> idx2 = data.a.values
>>> idx2
array([ 1, 10, 20], dtype=int64)
>>> data2 = DataFrame(data,index=idx2,columns=col[1:])
>>> data2
     b   c
1   11  12
10 NaN NaN
20 NaN NaN

知道为什么会这样吗?

推荐答案

为什么不简单地使用 set_index 方法?

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

这篇关于在Pandas DataFrame对象中重新定义索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 23:09