0

I have a dataframe with 2 columns : id , antecedent_id I would like a code to reorder the dataframe in the right order using antecedent_id. The first id is the one with antecedent_id empty

Dataframe example:

id antecedent_id
id1 id2
id4 id7
id6 id3
id7
id3 id4
id2 id6
id5 id1

The dataframe reordered should be like this:

id antecedent_id
id7
id4 id7
id3 id4
id6 id3
id2 id6
id1 id2
id5 id1

I would like to find the fastest code to do that as I have a huge number of rows

Thanks you so much for your help !

1
  • Welcome to StackOverflow! For future reference, please provide code used to construct the dataframe so that it is easier for people to reproduce your problem statement and answer your question Commented Feb 15, 2022 at 2:38

1 Answer 1

0

You basically want to sort the dataframe by values in a column:

import pandas as pd
df = pd.DataFrame({
    "id": ["id1", "id4", "id6", "id7", "id3", "id2", "id5"],
    "antecedent_id": ["id2", "id7", "id3", "", "id4", "id6", "id1"]
})
sorted_df = df.sort_values("antecedent_id", ascending=False)
print(sorted_df)

This code chunk returns a sorted dataframe like so:

    id antecedent_id
1  id4           id7
5  id2           id6
4  id3           id4
2  id6           id3
0  id1           id2
6  id5           id1
3  id7              
Sign up to request clarification or add additional context in comments.

1 Comment

I came to the same conclusion initially due to the phrase reorder the dataframe in the right order using antecedent_id, but this is very likely not what OP wanted. The outputs here don't match their expected output. What OP should have said is 'I have a directed graph (actually a path), where each node except the root has a unique antecedent (i.e. ancestor). Find this root, and perform a topological sort of the dataframe rows'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.