如何在保持列顺序的同时从多个 numpy
数组、Pandas
系列或 Pandas
DataFrame 创建一个 DataFrame?
例如,我有这两个 numpy
数组,我想将它们组合成一个 Pandas
DataFrame。
foo = np.array( [ 1, 2, 3 ] )
bar = np.array( [ 4, 5, 6 ] )
如果我这样做,bar
列会排在第一位,因为 dict
不保留顺序。
pd.DataFrame( { 'foo': pd.Series(foo), 'bar': pd.Series(bar) } )
bar foo
0 4 1
1 5 2
2 6 3
我可以这样做,但是当我需要组合许多变量时会变得乏味。
pd.DataFrame( { 'foo': pd.Series(foo), 'bar': pd.Series(bar) }, columns = [ 'foo', 'bar' ] )
编辑:有没有办法在一个操作中指定要连接的变量并组织列顺序?也就是说,我不介意使用多行来完成整个操作,但我宁愿不必指定要多次连接的变量(因为我将大量更改代码,这很容易出错) .
EDIT2:还有一点。如果我想添加或删除要加入的变量之一,我只想在一个地方添加/删除。
最佳答案
原解决方案:collections.OrderedDict
使用不正确
在我最初的解决方案中,我建议使用 python 标准库中 collections
包中的 OrderedDict
。
>>> 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 bar
0 1 4
1 2 5
2 3 6
正确的解决方案:传递键值元组对来保存订单
但是,如前所述,如果将普通字典传递给 OrderedDict
,则可能仍无法保留顺序,因为在构造字典时顺序是随机的。但是,一种解决方法是将键值元组对列表转换为 OrderedDict
,如 this SO post 中所建议的那样。 :
>>> 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 b
0 1 7 4
1 2 8 5
2 3 9 6
>>> pd.DataFrame( OrderedDict( (('a', pd.Series(a)), ('b', pd.Series(b)), ('c', pd.Series(c))) ) )
a b c
0 1 4 7
1 2 5 8
2 3 6 9
关于python - 如何在保留列顺序的同时创建 DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36539396/