2017-06-27 3 views
0

私は、pandasデータフレームのヘッダーをいくつかのパターンで注文したいというpythonプロジェクトに取り組んでいます。 マイ結果のリストは以下のようになります。部分的にリストを注文するPython

Match1 attribute1 attribute2 attribute3 ... attributeN Score1 Match2 attributeM Score2 ... Match3 Score3 

私は、リストにあるどのように多くのペアマッチ/スコアの知っている次のパターン

Match1 Score1 Match2 Score2 Match3 Score3 attribute1 attribute2 attributeN ... 

にリストの要素を注文したいです。しかし、私はどれくらいの属性があるかはわかりません(私はそれらを注文する必要はありません)。これらはすべてデータの特定の構造によって決まります。そのようなリストの順序を並べ替える方法はありますか?

ありがとうございます!

ご協力いただきありがとうございます。

答えて

1

sortedには、次のようにキーを指定できます。最初のキーは、ソート文字列の末尾に数で結果を最後に列を属性、および第二のキーの並べ替え:ここ

# cols = df.columns 
cols = ['Match1', 'attribute1', 'attribute2', 'attribute3', 'attributeN', 'Score1', 'Match2', 'attributeM', 'Score2', 'Match3', 'Score3'] 

import re 
sorted(cols, key=lambda x: (not bool(re.match('match|score', x, flags=re.I)), re.sub(r'.*(\d+)$', r'\1', x))) 

#['Match1', 
# 'Score1', 
# 'Match2', 
# 'Score2', 
# 'Match3', 
# 'Score3', 
# 'attribute1', 
# 'attribute2', 
# 'attribute3', 
# 'attributeM', 
# 'attributeN'] 
+0

おかげで開始するには、いくつかの不完全なコードです迅速な返信。ただし、属性はこの構造化されていません。彼らは名前の組み合わせを持っています。メソッドを変更することでそれを行う方法はまだありますか? – macintosh81

+0

鍵を逆向きにすることができます。一致とスコアの列が一致とスコアで始まると確信できる場合は、それらをチェックしてbool値を無効にすることができます。同様の結果が得られます。 – Psidom

+0

これはとてもうまく動作します!エレガントなソリューションをありがとう。 – macintosh81

1

は用

index = 0 
for i in range(num_matches_and_scores]: 
    match1 = ??? # First instance of whatever you are trying to find 
    list1.remove(match1) 
    list1.insert(index, match1) 
    index += 1 
    score1 = ??? 
    list1.remove(score1) 
    list1.inset(index, score1) 
    index += 1 
+0

私はそのアイデアを得て、それを実装しようとしました。ありがとう! – macintosh81

+0

これが最も有用な答えであれば、それを受け入れたとマークしていただければ幸いです。 :) –

関連する問題