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
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
CodePudding user response:
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)