JOHN JOHN -3 years ago 107
Python Question

why DataFrame in pandas arrange number before string?

data1 = {'key':['b','b','a','c','a','a','b'], 'data':range(7)}
df1 = pd.DataFrame(data1)


it is arranged as data, then follow by key. Why it is not arranged in key, then data?

Do I need to specify the columns?

Answer Source

data1 is a dictionary so the elements are stored in an arbitrary order. Now, the reason you see it in that specific order every time is because pandas frame constructor do sort the dictionary keys if there is no explicit columns argument.

Constructor simply uses:

>>> sorted(['key', 'data'])
['data', 'key']

So you are going to get the same ordering of columns every time. You can (have to) give the columns argument explicitly to store them in the order you want.

>>> pd.DataFrame(data1, columns=['key', 'data'])
  key  data
0   b     0
1   b     1
2   a     2
3   c     3
4   a     4
5   a     5
6   b     6
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download