# How to order a python dataframe by adding the row values?

I have the following dataframe:

    M1  M2  M4   M5
N1  45  46  54   57
N2  32  36  29   56
N3  56  44  40   55
N4  57  43  42   54


How is it possible to order it according to the sum of its lines, from the largest sum to the lowest? That is, N1 in the first line, because the sum of the line values ​​is the largest, then N4, N3 and finally N2 (because the sum of the values ​​is the smallest). Thus:

    M1  M2  M4   M5
N1  45  46  54   57
N4  57  43  42   54
N3  56  44  40   55
N2  32  36  29   56


You could simply create a sum column and then use sort_values. Afterwards, you can drop that column:

In [3]: df
Out[3]:
M1  M2  M4  M5
N1  45  46  54  57
N2  32  36  29  56
N3  56  44  40  55
N4  57  43  42  54

In [4]: df.sum(axis=1)
Out[4]:
N1    202
N2    153
N3    195
N4    196
dtype: int64

In [5]: df['sum'] = df.sum(axis=1)

In [6]: df
Out[6]:
M1  M2  M4  M5  sum
N1  45  46  54  57  202
N2  32  36  29  56  153
N3  56  44  40  55  195
N4  57  43  42  54  196

In [7]: df = df.sort_values("sum", ascending=False)

In [8]: df
Out[8]:
M1  M2  M4  M5  sum
N1  45  46  54  57  202
N4  57  43  42  54  196
N3  56  44  40  55  195
N2  32  36  29  56  153

In [9]: df = df.drop("sum", axis=1)

In [10]: df
Out[10]:
M1  M2  M4  M5
N1  45  46  54  57
N4  57  43  42  54
N3  56  44  40  55
N2  32  36  29  56

#create data
DF=pd.DataFrame(columns=["M1", "M2", "M3", "M4"])
DF.loc[0]=[45, 46, 54 , 57]
DF.loc[1]=[32 ,36 ,29 ,56]
DF.loc[2]=[56,44 ,40 ,55]
DF.loc[3]=[57 ,43 ,42 ,54]
DF=DF.astype(int)

#main function

DF["sum_"]=DF.apply(lambda x: sum(x), axis=1)
DF.sort_values("sum_", ascending=False)


You can first add a column that has the row sum, sort it, and then drop the new column.

test_data = pd.DataFrame(data = [[45, 46, 54, 57]
,[32, 3, 29, 56]
,[56, 44, 4, 55]
,[57, 43, 4, 54]
]
,columns=['M1', 'M2', 'M4', 'M5']
,index=['N1', 'N2', 'N3', 'N4']
)


test_data['row_sum'] = test_data.sum(axis=1) #sum across all columns


Sort and drop the new column

test_data.sort_values(by=['row_total'], ascending=False).drop(columns=['row_total'])


DataFrame.sort_values() will return the sorted DataFrame and we can drop the column from it

Alternatively, you can do this in one line

test_data.merge(
pd.Series(test_data.sum(axis=1), name='row_total'), how='inner', left_index=True, right_index=True)\
.sort_values(by=['row_total'], ascending=False)\
.drop(columns=['row_total'])


Explaining the code

1. Create a temporary pandas Series that contains the row sums
2. Merge the Series with the original DataFrame using index values
3. Sort on the new column
4. Drop the row sum column

Another way would be to take the sum, sort it and then use the index to reorder the original dataframe

df.loc[df.sum(axis=1).sort_values().index]