0

Goal:

Create columns

fst_imp: return column name in which value is index of the min value of each row.

snd_imp: value is column name in which value is index of the second small value of each row.

trd_imp: value is column name in which value is index of the third small value of each row.

Example result:

   A  B  C  fst_imp  snd_imp trd_imp
0  1  2  3   A         B      C
1  6  5  4   C         B      A
2  7  9  8   A         C      B

1 Answer 1

3

Here is one potential solution using numpy.argsort, the pandas.DataFrame constructor and DataFrame.join:

# Setup
import numpy as np
df = pd.DataFrame({'A': {0: 1, 1: 6, 2: 7}, 'B': {0: 2, 1: 5, 2: 9}, 'C': {0: 3, 1: 4, 2: 8}})

df.join(pd.DataFrame([df.columns.values[x] for x in np.argsort(df.values)],
                     columns=['fst_imp', 'snd_imp', 'trd_imp']))

[out]

   A  B  C fst_imp snd_imp trd_imp
0  1  2  3       A       B       C
1  6  5  4       C       B       A
2  7  9  8       A       C       B

Or a bit more scalable...

df.join(pd.DataFrame([df.columns.values[x] for x in np.argsort(df.values)]))

[out]

   A  B  C       0       1       2
0  1  2  3       A       B       C
1  6  5  4       C       B       A
2  7  9  8       A       C       B
Sign up to request clarification or add additional context in comments.

3 Comments

but if I have more than 3 columns,it will get AssertionError: 3 columns passed, passed data had N columns
remove the columns=[...] arg in that case, should work ok, you may just need a different way of renaming those column headings
pd.DataFrame([df.columns.values[x][:3] for x in np.argsort(df.values)], columns=['fst_imp', 'snd_imp', 'trd_imp']) it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.