Home > Software engineering >  Sorting Values by rows in data frame
Sorting Values by rows in data frame

Time:07-05

I hope you are well. I have a 4 column data frame with numerical values and Nan. What I need is to put the largest numbers in the first columns so that always the first column has the maximum value and the second column the next maximum value.

for x in Exapand_re_metrs[0]:
    for y in Exapand_re_metrs[1]:
        for z in Exapand_re_metrs[2]:
            for a in Exapand_re_metrs[3]:
                lista=[x,y,z,a]
                lista.sort()
                df["AREA_Mayor"]=lista[0]
                df["AREA_Menor"]=lista[1]

THE DF

CodePudding user response:

I'm not so sure what you want to do but here is a solution according to what I understood:

From what I see you have a dataframe with several columns and you would like it to be grouped in a single column with the values ​​from highest to lowest, so I will create a dataframe with almost the same characteristics as follows:

import pandas as pd
import numpy as np

cols = 3
rows = 4
np.random.seed(0)
df = pd.DataFrame(np.random.randint(0, 1000, (rows, cols)), columns= ["A","B","C"])

print(df)

     A    B    C
0  684  559  629
1  192  835  763
2  707  359    9
3  723  277  754

Now I will group all the columns in a single row and organize them in descending order like this:

data = df.to_numpy().flatten() 
data = pd.DataFrame(data)
data.sort_values(by=[0],ascending=False)

So as a result we will obtain a 1xn matrix where the values ​​are in descending order:

    0
4   835
5   763
11  754
9   723
6   707
0   684
2   629
1   559
7   359
10  277
3   192
8   9

Psdt: This code fragment should be adapted to your script; I didn't do it because I don't know your dataset and lastly my English is not that good sorry for any grammatical errors

CodePudding user response:

Exapand_re_metrs=Exapand_re_metrs.fillna(0)

df['mtrs']= Exapand_re_metrs.values.tolist()


df["mtrs"] = df["mtrs"].apply(sorted, reverse=True)
  • Related