2017-01-31 24 views
28

有沒有一種方法可以根據我的個人偏好重新排列熊貓數據框中的列(即不按字母順序或數字排序,但更像是遵循某些約定)?在熊貓數據框中設置列的順序

簡單的例子:

frame = pd.DataFrame({ 
     'one thing':[1,2,3,4], 
     'second thing':[0.1,0.2,1,2], 
     'other thing':['a','e','i','o']}) 

產生這樣的:

one thing other thing second thing 
0   1   a   0.1 
1   2   e   0.2 
2   3   i   1.0 
3   4   o   2.0 

但是,相反,我想這樣的:

one thing second thing other thing 
0   1   0.1   a 
1   2   0.2   e 
2   3   1.0   i 
3   4   2.0   o 

(請提供一個通用的解決方案,而不是具體到這種情況非常感謝。)

回答

38

只需通過輸入列名稱自行選擇訂單。注意雙括號:

frame = frame[['column I want first', 'column I want second'...etc.]] 
10

你也可以做類似df = df[['x', 'y', 'a', 'b']]

import pandas as pd 
frame = pd.DataFrame({'one thing':[1,2,3,4],'second thing':[0.1,0.2,1,2],'other thing':['a','e','i','o']}) 
frame = frame[['second thing', 'other thing', 'one thing']] 
print frame 
    second thing other thing one thing 
0   0.1   a   1 
1   0.2   e   2 
2   1.0   i   3 
3   2.0   o   4 

此外,您還可以得到列有清單:

cols = list(df.columns.values) 

輸出會產生類似這個:

['x', 'y', 'a', 'b'] 

然後便於手動重新排列。

5

您還可以使用OrderedDict:

In [183]: from collections import OrderedDict 

In [184]: data = OrderedDict() 

In [185]: data['one thing'] = [1,2,3,4] 

In [186]: data['second thing'] = [0.1,0.2,1,2] 

In [187]: data['other thing'] = ['a','e','i','o'] 

In [188]: frame = pd.DataFrame(data) 

In [189]: frame 
Out[189]: 
    one thing second thing other thing 
0   1   0.1   a 
1   2   0.2   e 
2   3   1.0   i 
3   4   2.0   o 
8

一個列表,而不是一本字典建設社會主義

frame = pd.DataFrame([ 
     [1, .1, 'a'], 
     [2, .2, 'e'], 
     [3, 1, 'i'], 
     [4, 4, 'o'] 
    ], columns=['one thing', 'second thing', 'other thing']) 

frame 

    one thing second thing other thing 
0   1   0.1   a 
1   2   0.2   e 
2   3   1.0   i 
3   4   4.0   o 
7

您可以使用此:

columnsTitles = ['onething', 'secondthing', 'otherthing'] 

frame.reindex(columns=columnsTitles)