4

Say you have, for a network G, the following dict with (Node ID, number of links), and say you want to dump it to a Pandas DataFrame:

import pandas as pd
import networkx as nx

degree=pd.DataFrame({'Node ID':G.degree().keys(),'Degree':G.degree().values()})
degree=degree[['Node ID','Degree']] #re-order

You obtain this:

In[1]: degree.head(5)
Out[1]:
     Node ID  Degree
0    0        19
1    1        117
2    2        13
3    3        56
4    4        15

Now say you want to sort this DataFrame with respect to the Degree column, in descending order. If I do this

sort_degree=degree.sort_values(['Node ID', 'Degree'], ascending=[False, False], inplace=False)

I don't get what I want:

    Node ID  Degree
4   4        15
3   3        56
2   2        13
1   1        117
0   0        19

What's wrong?

1
  • 3
    Why don't you just sort by the 'Degree' column only? sort_degree=degree.sort_values('Degree', ascending=False) Commented Oct 20, 2016 at 15:09

1 Answer 1

4

Seems to me you only need to sort by the Degree column:

In [156]:
sort_df = df.sort_values('Degree', ascending=False)
sort_df

Out[156]:
   Node ID  Degree
1        1     117
3        3      56
0        0      19
4        4      15
2        2      13

When you pass multiple columns then it will sort by those columns in the order they are passed, see the docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html#pandas.DataFrame.sort_values

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.