python - Order dataframe by row -
suppose have following dataframe
c1 c2 john 4 3 bob 5 7 mary 6 5 carl 5 6 james 4 3
how can order dataframe have:
carl, mary, bob, john, james
in efficient way?
it arbitrary ordering , might have names stored in variable orderednames
define ordering
arbitrary_ordering = ['carl', 'mary', 'bob', 'john', 'james']
option 1
loc
df.loc[arbitrary_ordering]
option 2
reindex
df.reindex(arbitrary_ordering)
option 3
reindex_axis
df.reindex_axis(arbitrary_ordering)
all yield
c1 c2 carl 5 6 mary 6 5 bob 5 7 john 4 3 james 4 3
alternative 1
df.iloc[df.index.to_series().map(arbitrary_ordering.index)]
alternative 2
pd.categorical
df.index = pd.categorical(df.index, categories=arbitrary_ordering) df.sort_index()
time test
Comments
Post a Comment