0

I have this sequence:

Dataframe sequence.

And the result that I expect is:

Sequence order.

It should be finished with the last row with: 5816993 - 0 I have 3 different dataframes where I shoud apply the same order, the only thing that I know is the finish of the sequence [5816993 - 0]

Dataframe:

df_1['IN'] = [5797067,5801307,5801615,5802487,5802839,5803163,5803579,5804175,5804947,5805287,5805559,5816775,5816957,5816993,5817055]
df_1['OUT'] = [5801307, 5801615, 5802487, 5802839, 5803163, 5803579,5804175, 5804947, 5805559, 5816775, 5805287, 5817055, 5816993,0,5816957]

I hope that someone can help me to find the rest part or some tips are very welcome.

Thanks guys!!

I only can get the part of the end [5816993 - 0]

With this code:

for i, row in df_1.iterrows():
    if df_2.empty:
        x = df_1.loc[df_1['OUT'] == 0]
        df_2['IN'] = x['IN']
        df_2['OUT'] = x['OUT']
        print('Estoy con DF Vacio {}'.format(i))
    
    else:
        pass
Klaus_84
  • 1
  • 1
  • I don't understand why you can't just sort. There is literally a method to do this for you. – Dan Dec 11 '22 at 23:00

1 Answers1

0

Are you looking for an overall order that is consistent with each row's IN --> OUT constraint?

If that is the case, then it is a good job for topological_sort.

With this:

r = topological_sort(df[['IN', 'OUT']].values.tolist())

>>> r
Results(sorted=[
    5797067, 5801307, 5801615, 5802487, 5802839, 5803163,
    5803579, 5804175, 5804947, 5805559, 5805287, 5816775,
    5817055, 5816957, 5816993, 0], cyclic=[])

# since there are no cycles, we can do:

assert not r.cyclic
ix = pd.Index(r.sorted, name='IN').intersection(df['IN'])
dfnew = df.set_index('IN').reindex(ix).reset_index()

>>> dfnew
         IN      OUT
0   5797067  5801307
1   5801307  5801615
2   5801615  5802487
3   5802487  5802839
4   5802839  5803163
5   5803163  5803579
6   5803579  5804175
7   5804175  5804947
8   5804947  5805559
9   5805559  5805287
10  5805287  5816775
11  5816775  5817055
12  5817055  5816957
13  5816957  5816993
14  5816993        0
Pierre D
  • 24,012
  • 7
  • 60
  • 96