简体   繁体   中英

Sorting multiple Pandas Dataframe Columns based on the sorting of one column

I have a dataframe with two columns in it,'item' and 'calories'. I have sorted the 'calories' column numerically using a selection sort algorithm, but i need the 'item' column to change so the calorie value matches the correct item.

menu=pd.read_csv("menu.csv",encoding="utf-8")   # Read in the csv file
menu_df=pd.DataFrame(menu,columns=['Item','Calories'])    # Creating a dataframe with just the information from the calories column
print(menu_df)                                  # Display un-sorted data
#print(menu_df.at[4,'Calories'])                # Practise calling on individual elements within the dataframe.

# Start of selection sort
for outerloopindex in range (len(menu_df)):   
    smallest_value_index=outerloopindex              
    for innerloopindex in range(outerloopindex+1,len(menu_df)):
        if menu_df.at[smallest_value_index,'Calories']>menu_df.at[innerloopindex,'Calories']:                                     
            smallest_value_index=innerloopindex                                                    
 
            
# Changing the order of the Calorie column.
    menu_df.at[outerloopindex,'Calories'],menu_df.at[smallest_value_index,'Calories']=menu_df.at[smallest_value_index,'Calories'],menu_df.at[outerloopindex,'Calories']     

# End of selection sort

print(menu_df) 

Any help on how to get the 'Item' column to match the corresponding 'Calorie' values after the sort would be really really appreciated.

Thanks Martin

You can replace df.at[...] with df.loc[...] and refer multiple columns, instead of single one.

So replace line:

menu_df.at[outerloopindex,'Calories'],menu_df.at[smallest_value_index,'Calories']=menu_df.at[smallest_value_index,'Calories'],menu_df.at[outerloopindex,'Calories']     

With line:

menu_df.loc[outerloopindex,['Calories','Item']],menu_df.loc[smallest_value_index,['Calories','Item']]=menu_df.loc[smallest_value_index,['Calories','Item']],menu_df.loc[outerloopindex,['Calories','Item']]     

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