Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a pandas dataframe from dictionary whilst maintaining order of columns

When creating a dataframe as below (instructions from here), the order of the columns changes from "Day, Visitors, Bounce Rate" to "Bounce Rate, Day, Visitors"

import pandas as pd

web_stats = {'Day':[1,2,3,4,5,6],
             'Visitors':[43,34,65,56,29,76],
             'Bounce Rate':[65,67,78,65,45,52]}

df = pd.DataFrame(web_stats)

Gives:

Bounce Rate  Day  Visitors

0  65           1    43      
1  67           2    34      
2  78           3    65      
3  65           4    56      
4  45           5    29      
5  52           6    76 

How can the order be kept in tact? (i.e. Day, Visitors, Bounce Rate)

like image 553
stevec Avatar asked Dec 07 '25 06:12

stevec


2 Answers

One approach is to use columns

Ex:

import pandas as pd

web_stats = {'Day':[1,2,3,4,5,6],
             'Visitors':[43,34,65,56,29,76],
             'Bounce Rate':[65,67,78,65,45,52]}

df = pd.DataFrame(web_stats, columns = ['Day', 'Visitors', 'Bounce Rate'])
print(df)

Output:

   Day  Visitors  Bounce Rate
0    1        43           65
1    2        34           67
2    3        65           78
3    4        56           65
4    5        29           45
5    6        76           52
like image 144
Rakesh Avatar answered Dec 09 '25 19:12

Rakesh


Dictionaries are not considered to be ordered in Python <3.7.

You can use collections.OrderedDict instead:

from collections import OrderedDict

web_stats = OrderedDict([('Day', [1,2,3,4,5,6]),
                         ('Visitors', [43,34,65,56,29,76]),
                         ('Bounce Rate', [65,67,78,65,45,52])])

df = pd.DataFrame(web_stats)
like image 38
jpp Avatar answered Dec 09 '25 21:12

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!