Created
July 27, 2015 12:26
-
-
Save hellpanderrr/599bce82ecc6934aa9e1 to your computer and use it in GitHub Desktop.
Pandas sort dataframe using custom function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
.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
Shorter version: