1

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

1 Answer 1

1

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.

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

1 Comment

@jezrael no clue, I flagged a post to moderators once but got no feedback, I think I've had dozen of those… (see here for example)