Pandas: create a frame without automatically sorting column names in alphabetical order

I am creating an initial pandas framework to store the results generated by other codes: for example,

result = pd.DataFrame({'date': datelist, 'total': [0]*len(datelist), 
                       'TT': [0]*len(datelist)})

with a datelistpredefined list. Then the other codes will give out a number for totaland TTfor each date, which I will keep in the frame result.

So, I want the first column to be date, the second totaland third TT. However, the pandas will automatically change the order in alphabetical order TT, date, totalto create. While I can manually reorder after this, I wonder if there is an easier way to achieve this in one step.

I thought I could do and

result = pd.DataFrame(np.transpose([datelist, [0]*l, [0]*l]),
                      columns = ['date', 'total', 'TT'])

but it somehow looks tiring too. Any other suggestions?

+4
source share
2 answers

You can pass a (properly ordered) list of columns as a parameter to the constructor, or use OrderedDict:

# option 1:
result = pd.DataFrame({'date': datelist, 'total': [0]*len(datelist), 
                   'TT': [0]*len(datelist)}, columns=['date', 'total', 'TT'])

# option 2:
od = collections.OrderedDict()
od['date'] = datelist
od['total'] = [0]*len(datelist)
od['TT'] = [0]*len(datelist)
result = pd.DataFrame(od)
+8
source
result = pd.DataFrame({'date': [23,24], 'total': 0,
                       'TT': 0},columns=['date','total','TT'])
+1
source

Source: https://habr.com/ru/post/1656740/


All Articles