Search code examples
pythonpandassortingdendrogram

Sort pandas DataFrame rows by a list of (index) numbers


I have a pandas DataFrame with 229 rows. I have a list of index numbers ([47, 16, 59, ...]) and I want to re-sort the rows of my DataFrame into this order.

Details: I ran the DF through a filter (specifically, scipy.cluster.hierarchy.dendrogram, setting get_leaves=True). The return value includes a list of index numbers (leaves) in order of the dendrogram leaf nodes. I now want to sort my DF in that order, so that I can plot the clusters.

I'm sure there are many ways that I can merge a bunch of tables and drop columns but... is there a nice idiomatic way to do this?


Solution

  • if the list is the same shape as df then just paste it in like so and sort by newly created column

    df['List']=ListOfIndices
    df.sort_values(by=['List'])