简体   繁体   English

pandas 数据框(或 python 列表/元组)的排序问题

[英]Sorting issue with pandas dataframe (or python list/tuple)

I have a pandas DataFrame which looks like this:我有一个如下所示的 Pandas DataFrame:

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).它按第二列 (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.也就是说,第二列 (uid) 中的值决定了数据帧/列表中的下一个特定行,但并不总是如您所见。 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.在它的原始形状中,它是按 uid 列排序的,直到有一行带有指向该 uid 的引用键为止。

The solution does not have to be a pandas/dataframe one, pure python solution also will work.解决方案不一定是熊猫/数据框,纯 python 解决方案也可以。

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'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM