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 sort multiple column data by the first character and the value

I’m new to pandas and i wanna try sort a data by its name and its value,

example:

zeta,3
zxta,1
beta,5

I want to sort it to

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

beta,5
zxta,1
zeta,3

I tried using pandas sort function

import pandas as pd

df.to_csv("testdat.csv")

df.sort_values(["name","val"],ascending=[1,1])

but it show me the data like this instead

beta,5
zeta,3
zxta,1

>Solution :

You can add another column based on the first character of your name column then remove it after that

import pandas as pd

names = ['zeta','zxta','beta']
vals = [3,1,5]
data = {'name': names,'val':vals}
df = pd.DataFrame(data, columns = ['name', 'val'])
temp = [name[:1] for name in names]
df['temp'] = temp
df = df.sort_values(["temp","val"],ascending=[1,1])
df.drop('temp', inplace=True, axis=1)
print(df)
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