Home > Enterprise >  sort a selection of a pandas dataframe only (keep some columns fixed)
sort a selection of a pandas dataframe only (keep some columns fixed)

Time:06-13

import pandas as pd
 
data = {'Brand': ['HH','TT','FF','AA'],
        'Price': [22000,25000,27000,35000],
        'Year': [2015,2013,2018,2018],
        'Misc1': ['Description: ', '', '', ''],
        'Misc2': ['Car Prices 2022', '', '', '']        
        }
 
df = pd.DataFrame(data, columns=['Brand','Price','Year', 'Misc1', 'Misc2'])
print (df, '\n')

df.sort_values(by=['Brand'], inplace=True)
print(df, '\n')

I would like to keep Misc1 and Misc2 columns fixed

this does not work

df = df.loc[:, ~df.columns.isin(['Misc1', 'Misc2'])].sort_values(by=['Brand'], inplace=True)
print(df,'\n')

does anybody here know a good way to do this?

CodePudding user response:

here is one way to do it

breakup your DF into two DFs, while resetting the index on first one

df2=df[['Brand','Price','Year']].sort_values(by=['Brand'] ).reset_index()
df3=df[['Misc1','Misc2']]

join the two DFs

df2.join(df3).drop(columns='index')
    Brand   Price   Year    Misc1           Misc2
0   AA      35000   2018    Description:    Car Prices 2022
1   FF      27000   2018        
2   HH      22000   2015        
3   TT      25000   2013                

here is the original DF, before sort

    Brand   Price   Year    Misc1           Misc2
0   HH      22000   2015    Description:    Car Prices 2022
1   TT      25000   2013        
2   FF      27000   2018        
3   AA      35000   2018        

CodePudding user response:

IIUC, you can assign the Misc column back after sorting

out = df.sort_values(by=['Brand'])
out[['Misc1', 'Misc2']] = df[['Misc1', 'Misc2']].values
print(out)

  Brand  Price  Year          Misc1            Misc2
3    AA  35000  2018  Description:   Car Prices 2022
2    FF  27000  2018
0    HH  22000  2015
1    TT  25000  2013
  • Related