Pandas —— set_index( )将DataFrame的列转换为行索引

In [42]: frame=pd.DataFrame({'a':range(7),'b':range(7,0,-1),
    ...: 'c':['one','one','one','two','two','two','two'],
    ...: 'd':[0,1,2,0,1,2,3]})

In [43]: frame
Out[43]:
   a  b    c  d
0  0  7  one  0
1  1  6  one  1
2  2  5  one  2
3  3  4  two  0
4  4  3  two  1
5  5  2  two  2
6  6  1  two  3

DataFrame的set_index( )函数会将一个或多个列转换为行索引

In [44]: frame.set_index(['c','d'])
Out[44]:
       a  b
c   d
one 0  0  7
    1  1  6
    2  2  5
two 0  3  4
    1  4  3
    2  5  2
    3  6  1

默认情况下,转换的列会从DataFrame中移除,但也可以将其保留下来

In [47]: frame.set_index(['c','d'],drop=False)
Out[47]:
       a  b    c  d
c   d
one 0  0  7  one  0
    1  1  6  one  1
    2  2  5  one  2
two 0  3  4  two  0
    1  4  3  two  1
    2  5  2  two  2
    3  6  1  two  3

reset_index( )是set_index( )的逆运算

In [45]: frame.set_index(['c','d']).reset_index()
Out[45]:
     c  d  a  b
0  one  0  0  7
1  one  1  1  6
2  one  2  2  5
3  two  0  3  4
4  two  1  4  3
5  two  2  5  2
6  two  3  6  1

转载地址:

《利用Python进行数据分析》

你可能感兴趣的:(Pandas)