は、2つの方法があり、両方のFind names of top-n highest-value columns in each pandas dataframe row
から@ unutbuの答えから適応します
1)列名を挿入するには、各行に.apply(lambda ...)
というPython Decorate-Sort-Undecorateを使用し、np.argsortを実行し、トップnを保持して、応答を再フォーマットします。 (私はこれがよりクリーンだと思う)。次のように
import numpy as np
# First we apply Decorate-Sort row-wise to our df...
tmp = df.apply(lambda row: sorted(zip(df.columns, row), key=lambda cv: -cv[1]), axis=1)
a b c
0 (b, 4) (a, 1) (c, 0)
1 (b, 6) (c, 4) (a, 2)
2 (c, 8) (a, 1) (b, 0)
# Slice the top-n columns within each row...
tmp = tmp.ix[:,0:nlargest]
# then your result (as a pandas DataFrame) is...
np.array(tmp)
array([[('b', 4), ('a', 1)],
[('b', 6), ('c', 4)],
[('c', 8), ('a', 1)]], dtype=object)
# ... or as a list of rows is
tmp.values.tolist()
#... and you can insert the row-indices 0,1,2 with
zip(tmp.index, tmp.values.tolist())
[(0, [('b', 4), ('a', 1), ('c', 0)]), (1, [('b', 6), ('c', 4), ('a', 2)]), (2, [('c', 8), ('a', 1), ('b', 0)])]
2)df.columns、及びdf.valuesに再インデックス、及びその出力を結合することの両方を使用し、その後、topnlocs
の行列を取得します。
import numpy as np
nlargest = 2
topnlocs = np.argsort(-df.values, axis=1)[:, 0:nlargest]
# ... now you can use topnlocs to reindex both into df.columns, and df.values, then reformat/combine them somehow
# however it's painful trying to apply that NumPy array of indices back to df or df.values,
はHow to get away with a multidimensional index in pandas
は、それが正確に3つの列であり、その名前は '、B、C 'であるか、あなたは一般的な答えをしたいですかということが保証されていますか? – smci
私は一般的な答えをしたい、単純にするために3つの列を使用しました –
[データフレームの各行に対して上位N列を選択する]の可能な複製(http://stackoverflow.com/questions/34297319/selecting-top-n - 列ごとにデータフレームの行に) – smci