JrCaspian
JrCaspian

Reputation: 327

DataFrame sorting unwanted using Pandas

Consider a basic data frame (using Pandas):

testDf = pandas.DataFrame({'c':[1,2],'b':[2,2],'a':[3,4]})

The result gives:

   a  b  c
0  3  2  1
1  4  2  2

Instead of:

   c  b  a
0  1  2  3
1  2  2  4

Why is it sorted alphabetically? I want the second result.

Upvotes: 4

Views: 1078

Answers (3)

jezrael
jezrael

Reputation: 862661

You need add parameter columns to DataFrame constructor, because dict is unordered:

print (pd.DataFrame({'c':[1,2],'b':[2,2],'a':[3,4]}, columns=['c','b','a']))
   c  b  a
0  1  2  3
1  2  2  4

Dataframe:

Along with the data, you can optionally pass index (row labels) and columns (column labels) arguments. If you pass an index and / or columns, you are guaranteeing the index and / or columns of the resulting DataFrame. Thus, a dict of Series plus a specific index will discard all data not matching up to the passed index.

Upvotes: 3

EdChum
EdChum

Reputation: 394041

You passed a dict as the data param so the order is not the same as the order of key creation as the order is not the same, you can specify the column order by passing a list of the columns as the arg for columns param:

In [307]:
testDf = pd.DataFrame({'c':[1,2],'b':[2,2],'a':[3,4]}, columns=['c','b','a'])
testDf

Out[307]:
   c  b  a
0  1  2  3
1  2  2  4

Upvotes: 2

Mathias711
Mathias711

Reputation: 6658

A dictionary is unsorted, therefor you cannot expect the ordering to be the same as in the initialization.

Upvotes: 0

Related Questions