user16627746
user16627746

Reputation:

Why my pandas DataFrame didn't sort columns?

I'm following the book "Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython 2nd Edition, by Wes McKinne" and the book said, pandas DataFrame automaticaly sort columns by its name.

book example

But what I tried didn't sort columns. it order just what I order.

why? The book was wrong?

perfectly same code

Upvotes: 1

Views: 54

Answers (1)

mozway
mozway

Reputation: 260420

Dictionaries used to be unordered, since python3.7, the order of keys in a dictionary is guaranteed.

python2.7:

>>> {'b': 0, 'a': 1, 'c': 2}
{'a': 1, 'c': 2, 'b': 0}

python3.7:

>>> {'b': 0, 'a': 1, 'c': 2}
{'b': 0, 'a': 1, 'c': 2}

So, the book is wrong for recent python (I guess it was written a while ago). Anyway, before that, the order was not to be relied on, so this could have worked by implementation but was not reliable.

Upvotes: 1

Related Questions