原始解决方案:错误使用 collections.OrderedDict
在我最初的解决方案中,我建议使用python标准库中
OrderedDict的
collections包。
>>> import numpy as np>>> import pandas as pd>>> from collections import OrderedDict>>>>>> foo = np.array( [ 1, 2, 3 ] )>>> bar = np.array( [ 4, 5, 6 ] )>>>>>> pd.Dataframe( OrderedDict( { 'foo': pd.Series(foo), 'bar': pd.Series(bar) } ) ) foo bar0 1 41 2 52 3 6正确的解决方案:传递键值元组对以保留订单
但是,如前所述,如果将普通字典传递给
OrderedDict,则顺序可能仍然无法保留,因为在构造字典时该顺序是随机的。但是,一种解决方法是将键值元组对的列表转换为
OrderedDict,如下面的SO建议:
>>> import numpy as np>>> import pandas as pd>>> from collections import OrderedDict>>>>>> a = np.array( [ 1, 2, 3 ] )>>> b = np.array( [ 4, 5, 6 ] )>>> c = np.array( [ 7, 8, 9 ] )>>>>>> pd.Dataframe( OrderedDict( { 'a': pd.Series(a), 'b': pd.Series(b), 'c': pd.Series(c) } ) ) a c b0 1 7 41 2 8 52 3 9 6>>> pd.Dataframe( OrderedDict( (('a', pd.Series(a)), ('b', pd.Series(b)), ('c', pd.Series(c))) ) ) a b c0 1 4 71 2 5 82 3 6 9


