Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort networkx edgelist by 2 edge attributes

I want to sort this edgelist by 2 edge attributes descending in value.

df_test = pd.DataFrame({'A':['AXQ00084.1', 'AXQ00134.1', 'AZI75768.1', 'AZI75768.1','AZI75801.1','AZI75801.1'],
                         'B':['AZI75768.1', 'AZI75768.1', 'AXQ00084.1', 'AXQ00134.1','AXQ00106.1','AXQ00107.1'],
                         'X': [607, 272, 595, 323,30,30],
                         'Y':[99.675, 83.23, 97.70, 98.78,97,99]})

g2 = nx.from_pandas_edgelist(df_test, 'A', 'B', edge_attr=['X','Y'])
g2.edges(data=True)
g_dict = sorted(g2.edges(data=True),key= lambda x: x[1][2],reverse=False)

g_dict returns:

[('AXQ00084.1', 'AZI75768.1', {'X': 595, 'Y': 97.7}),
 ('AZI75768.1', 'AXQ00134.1', {'X': 323, 'Y': 98.78}),
 ('AZI75801.1', 'AXQ00106.1', {'X': 30, 'Y': 97.0}),
 ('AZI75801.1', 'AXQ00107.1', {'X': 30, 'Y': 99.0})]

When the desired output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 [('AXQ00084.1', 'AZI75768.1', {'X': 595, 'Y': 97.7}),
 ('AZI75768.1', 'AXQ00134.1', {'X': 323, 'Y': 98.78}),
 ('AZI75801.1', 'AXQ00107.1', {'X': 30, 'Y': 99.0}),
 ('AZI75801.1', 'AXQ00106.1', {'X': 30, 'Y': 97.0})]

>Solution :

Use a tuple of the dictionary values:

g_dict = sorted(g2.edges(data=True),
                key=lambda x: (x[2]['X'], x[2]['Y']),
                reverse=True)

more generic approach in case you have many keys to handle:

from operator import itemgetter
g_dict = sorted(g2.edges(data=True),
                key=lambda x: itemgetter('X', 'Y')(x[2]),
                reverse=True)

output:

[('AXQ00084.1', 'AZI75768.1', {'X': 595, 'Y': 97.7}),
 ('AZI75768.1', 'AXQ00134.1', {'X': 323, 'Y': 98.78}),
 ('AZI75801.1', 'AXQ00107.1', {'X': 30, 'Y': 99.0}),
 ('AZI75801.1', 'AXQ00106.1', {'X': 30, 'Y': 97.0})]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading