Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add "orderd data" wity apply method in pandas (not use for-loop)

ID A B C D Orderd
No1 8 9 5 2 D:2 C:5 A:8 B:9
No2 3 1 7 9 B:1 A:3 C:7 D:9
No3 29 34 5 294 C:5 A:29 B:34 D:294

I would like to add "Orderd" column with column of A, B, C and D.

If I use for loop, I can do it as like

for n in range(len(df)):
    df['Orderd'][n] = df.T.sort_values(by=n,ascending=True)[n].to_string()

However, this method is too slow. I would like to do like this with "df.apply" method for doing speedy.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use apply directly on your dataframe, indicating the axis = 1

import pandas as pd

columns = ["ID","A","B","C","D"]
data = [["No1",8,9,5,2],
        ["No2",3,1,7,9],
        ["No3",29,34,5,294]]

df = pd.DataFrame(data=data, columns=columns)
df = df.set_index("ID") # important to avoid having an error

df["Orderd"] = df.apply(lambda x: x.sort_values().to_dict(), axis=1)

outputs:

   A   B   C   D   Orderd
ID                  
No1     8   9   5   2   {'D': 2, 'C': 5, 'A': 8, 'B': 9}
No2     3   1   7   9   {'B': 1, 'A': 3, 'C': 7, 'D': 9}
No3     29  34  5   294     {'C': 5, 'A': 29, 'B': 34, 'D': 294}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading