I have a pandas DataFrame which looks like this:
import pandas as pd
data = [
(638009197035522, 655784141500417), # 0
(693075572527105, 693075572527105), # 1
(655784141500417, 693668642918400), # 2
(693075572527105, 694397537353729), # 3
(694397537353729, 695737600794624), # 4
(695737600794624, 700168400654337), # 5
(693075572527105, 929811762360322), # 6
(929811762360322, 931830115979265), # 7
(931830115979265, 951912745500672), # 8
(951912745500672, 965073687117824)] # 9
pd.DataFrame(data, columns=['reference', 'uid'])
It is sorted by the second column (uid). What I would like to achieve, however, is to sort (or rebuild) dataframe in a way that it will look like as follows:
[(638009197035522, 655784141500417), # 0->0
(655784141500417, 693668642918400), # 2->1
(693075572527105, 693075572527105), # 1->2
(693075572527105, 694397537353729), # 3->3
(694397537353729, 695737600794624), # 4->4
(693075572527105, 929811762360322), # 6->5
(695737600794624, 700168400654337), # 5->6
(929811762360322, 931830115979265), # 7->7
(931830115979265, 951912745500672), # 8->8
(951912745500672, 965073687117824)] # 9->9
That is, the value in the second column (uid) determines which specific row comes next in dataframe/list, but not always as you can see. In its original shape, it is sorted by the uid column, which is okay until there is a row with a reference key to this uid.
The solution does not have to be a pandas/dataframe one, pure python solution also will work.
df = pd.DataFrame(data, columns=['reference', 'uid'])
df.sort_values(by="reference", inplace=True)
df
reference uid
0 638009197035522 655784141500417
2 655784141500417 693668642918400
1 693075572527105 693075572527105
3 693075572527105 694397537353729
6 693075572527105 929811762360322
4 694397537353729 695737600794624
5 695737600794624 700168400654337
7 929811762360322 931830115979265
8 931830115979265 951912745500672
9 951912745500672 965073687117824
Then a further sort along the lines of
df['uid'].isin(df['reference'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.