Search code examples
pythonpandassortingindices

Mapping row-wise sorted dataframe to original column labels (Pandas), but only those having value greater than zero


I had asked a question here Mapping row-wise sorted dataframe to original column labels (Pandas) but, I wish to extend this problem by only having those column indices displayed whose corresponding value was greater than 0.

I am having a Dataframe -

df 
   A  B  C   D
0  8  3  6   2
1  1 -3  5   2
2  4  9  5  10
3  2 -4 -8  -2

I sort every row in descending order, and instead of saving the values, I save the corresponding column name, BUT with the condition that those column names whose corresponding values were negative are excluded.

Final result be:

df_col 
       1  2  3   4
    0  A  C  B   D
    1  C  D  A   
    2  D  B  C   A
    3  A  

Solution

  • You can use:

    df = df.apply(lambda x: pd.Series(x[x > 0].sort_values(ascending=False).index), axis=1)
    print (df)
       0    1    2    3
    0  A    C    B    D
    1  C    D    A  NaN
    2  D    B    C    A
    3  A  NaN  NaN  NaN