简体   繁体   中英

How to sort one column based on another column in Pandas Dataframe?

so suppose I have a dataframe with column names A,B and C. Now i want to only sort A on the basis of C and not B. df['A']=df['A'].sort_values(df['B]) does not work.

A bit of a roundabout way could be to subset the two columns you want to sort, sort them, and then add the unsorted column back into the new dataframe. Like this:

df2 = df[["A","C"]] # get columns A and C
df2 = df2.sortvalues("C") # sort df2 by C
df2["B"] = df["B"] # add column B back in its unsorted form

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM