Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hellpanderrr
Created July 27, 2015 12:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hellpanderrr/599bce82ecc6934aa9e1 to your computer and use it in GitHub Desktop.
Save hellpanderrr/599bce82ecc6934aa9e1 to your computer and use it in GitHub Desktop.
Pandas sort dataframe using custom function
def sort_df(df, column_idx, key):
'''Takes dataframe, column index and custom function for sorting,
returns dataframe sorted by this column using this function'''
col = df.ix[:,column_idx]
temp = pd.DataFrame([])
temp[0] = col
temp[1] = df.index
temp = temp.values.tolist()
df = df.ix[[i[1] for i in sorted(temp, key=key)]]
return df
@andreshp
Copy link

Shorter version:

def sort_df(df, column_idx, key):
    '''Takes dataframe, column index and custom function for sorting, 
    returns dataframe sorted by this column using this function'''
    
    col = df.ix[:,column_idx]
    temp = np.array(col.values.tolist())
    order = sorted(range(len(temp)), key=lambda j: key(temp[j]))
    return df.ix[order]

@alberand
Copy link

.ix is deprecated

def sort_df(df, column_idx, key):
    '''Takes dataframe, column index and custom function for sorting, 
    returns dataframe sorted by this column using this function'''
    
    col = df.iloc[:,column_idx]
    temp = np.array(col.values.tolist())
    order = sorted(range(len(temp)), key=lambda j: key(temp[j]))
    return df.iloc[order]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment