问题描述
我正在创建一个初始的熊猫数据框,以存储从其他代码生成的结果:例如
I am creating an initial pandas dataframe to store results generated from other codes: e.g.
result = pd.DataFrame({'date': datelist, 'total': [0]*len(datelist),
'TT': [0]*len(datelist)})
带有datelist
的预定义列表.然后其他代码将为每个date
输出total
和TT
的一些数字,这些数字将存储在result
数据框中.
with datelist
a predefined list. Then other codes will output some number for total
and TT
for each date
, which I will store in the result
dataframe.
所以我希望第一列是date
,第二列是total
和第三列TT
.但是,熊猫在创建时会自动按字母顺序将其重新排序为TT
,date
,total
.虽然我之后可以手动重新排序,但我想知道是否有一种更简单的方法可以一步完成.
So I want the first column to be date
, second total
and third TT
. However, pandas will automatically reorder it alphabetically to TT
, date
, total
at creation. While I can manually reorder this again afterwards, I wonder if there is an easier way to achieve this in one step.
我认为我也可以做到
result = pd.DataFrame(np.transpose([datelist, [0]*l, [0]*l]),
columns = ['date', 'total', 'TT'])
但是它看起来也很乏味.还有其他建议吗?
but it somehow also looks tedious. Any other suggestions?
推荐答案
您可以将列(正确排序)的列表作为参数传递给构造函数,或使用OrderedDict:
You can pass the (correctly ordered) list of column as parameter to the constructor or use an 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)
这篇关于 pandas :创建数据框时不按字母顺序自动排序列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!