I have a dataframe which contains post and comments. Every comment has an id and a parent id (identifies the comment or post which the comment was a response to). Posts only have an id, since they don't answer to anything.
| submission | id | parent id |
|---|---|---|
| post1 | 1 | |
| comment1 | 2 | 1 |
| comment2 | 3 | 1 |
| comment3 | 4 | 2 |
| comment4 | 5 | 4 |
| post2 | 6 | |
| comment5 | 7 | 6 |
I would like to retrieve the id of the original post for every comment and obtain something like that:
| submission | id | parent id | ancestor id |
|---|---|---|---|
| post1 | 1 | ||
| comment1 | 2 | 1 | 1 |
| comment2 | 3 | 1 | 1 |
| comment3 | 4 | 2 | 1 |
| comment4 | 5 | 4 | 1 |
| post2 | 6 | ||
| comment5 | 7 | 6 | 2 |
to do so I tried to loop from the end of the dataframe to the beginning, iteratively tracing back the parent_id of the parent_id until I found an empty parent_id cell. On the test dataframe it works, but on the main one is too slow. Is there a way to make it more efficient?
Here my original code:
#creating a column for the id of the original post
df["ancestor"] = df.id
#obtaining the id of the original post for every comment
for i in reversed(range(len(df.id))): #looping trough the comments
id = df["parent_id"][i] #variable to initialize the future loop
parent = id
while parent != "": #only looping trough comments
df.ancestor[i] = id
parent = df.parent_id[df.id == id].values[0]
id = parent