0

Could you explain to me why the Properties column was the third column and not the first one? As you can see I insert it as the first in pd.DataFrame, but when I do print(df), it appears as the third column.

import pandas as pd

df = pd.DataFrame({'Properties':[1, 2, 3,4],
                   'Latitude':[-24.930473, -24.95575,-24.924161,-24.95579],
                   'Longitude':[-24.930473, -24.95575,-24.924161,-24.95579],
                   'cluster': (1,2,1,2)})

print(df)

    Latitude  Longitude  Properties  cluster
0 -24.930473 -24.930473           1        1
1 -24.955750 -24.955750           2        2
2 -24.924161 -24.924161           3        1
3 -24.955790 -24.955790           4        2

enter image description here

  • Does this answer your question? https://stackoverflow.com/questions/36539396/how-to-create-a-dataframe-while-preserving-order-of-the-columns – medium-dimensional May 05 '22 at 22:55
  • 1
    what version of pandas and python are you on, because this works fine on pandas 1.4 and python 3.8 – sammywemmy May 06 '22 at 00:05
  • @sammywemmy, I saw now that I had the outdated version of `pandas`, after I updated it worked normally. Thanks for the message, –  May 06 '22 at 13:09

1 Answers1

0

Try using columns argument to assign the order of columns:

import pandas as pd
df = pd.DataFrame({'C1':[1, 2, 3,4],
                   'C2':[-24.930473, -24.95575,-24.924161,-24.95579],
                   'C3':[-24.930473, -24.95575,-24.924161,-24.95579],
                   'C4': (1,2,1,2)}, columns=['C1', 'C3', 'C2', 'C4'])

This gives:

   C1         C3         C2  C4
0   1 -24.930473 -24.930473   1
1   2 -24.955750 -24.955750   2
2   3 -24.924161 -24.924161   1
3   4 -24.955790 -24.955790   2
medium-dimensional
  • 1,974
  • 10
  • 19
  • Ok now @medium-dimensional, thanks for reply. Another thing is there any difference making `'cluster': (1,2,1,2)` or `'cluster': [1,2,1,2]`? I'm new to Python language. –  May 05 '22 at 23:05
  • `(1,2,1,2)` is a tuple, but `[1,2,1,2]` is a list. However, I am not sure if this difference leads to having different column order since I got the same result in both the cases. You can check if you see any difference in column order by changing `cluster` to a tuple or a list, and open a new question to understand what might be driving the difference. – medium-dimensional May 05 '22 at 23:18