简体   繁体   English

Pandas:创建数据帧而不按字母顺序自动排序列名

[英]Pandas: create dataframe without auto ordering column names alphabetically

I am creating an initial pandas dataframe to store results generated from other codes: eg 我正在创建一个初始的pandas数据帧来存储从其他代码生成的结果:例如

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

with datelist a predefined list. 使用datelist列表预定义列表。 Then other codes will output some number for total and TT for each date , which I will store in the result dataframe. 然后其他代码将为每个date输出一些totalTT ,我将存储在result数据框中。

So I want the first column to be date , second total and third TT . 所以我想的第一列是date ,第二个total第三TT However, pandas will automatically reorder it alphabetically to TT , date , total at creation. 但是,pandas会自动按字母顺序将其重新排序为TTdate ,创建时的total While I can manually reorder this again afterwards, I wonder if there is an easier way to achieve this in one step. 虽然我之后可以手动重新排序,但我想知道是否有更简单的方法可以一步到位。

I figured I can also do 我想我也可以

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

but it somehow also looks tedious. 但它在某种程度上看起来也很单调乏味。 Any other suggestions? 还有其他建议吗?

You can pass the (correctly ordered) list of column as parameter to the constructor or use an OrderedDict: 您可以将(正确排序的)列列表作为参数传递给构造函数或使用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)
result = pd.DataFrame({'date': [23,24], 'total': 0,
                       'TT': 0},columns=['date','total','TT'])

Use pandas >= 0.23 in combination with Python >= 3.6. 将pandas> = 0.23与Python> = 3.6结合使用。

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

retains the dict's insertion order when creating a DataFrame (or Series) from a dict when using pandas v0.23.0 in combination with Python3.6. 在将pandas v0.23.0与Python3.6结合使用时,在从dict创建DataFrame(或Series)时保留dict的插入顺序。

See https://pandas.pydata.org/pandas-docs/version/0.23.0/whatsnew.html#whatsnew-0230-api-breaking-dict-insertion-order . 请参阅https://pandas.pydata.org/pandas-docs/version/0.23.0/whatsnew.html#whatsnew-0230-api-breaking-dict-insertion-order

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM