2017-01-31 18 views
28

私の個人的な好み(アルファベット順または数値順ではなく、特定の規則に従う方が良い)に基づいて、pandasデータフレームの列を並べ替える方法はありますか?pandasデータフレームの列の順序を設定する

簡単な例:に

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 

(、汎用的なソリューションを提供してくださいではなく、具体的な:

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 

しかし、その代わりに、私はこれをしたいと思います:

frame = pd.DataFrame({ 
     'one thing':[1,2,3,4], 
     'second thing':[0.1,0.2,1,2], 
     'other thing':['a','e','i','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) 
関連する問題