Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

python - Redefining the Index in a Pandas DataFrame object

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

Any idea why this is happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...