python - 如何在保留列顺序的同时创建 DataFrame?

标签 python pandas

如何在保持列顺序的同时从多个 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/

相关文章:

python - 如何删除数据集中的重复值 : python

python - 使用 Python 将新行追加到 MySQL 数据库中的现有字段

python - 设置组件时 pyasn1 和奇怪的不匹配

Python格式化时间字符串到日期时间对象

python - 我想使用ElasticSearch 6或ElasticSearch 7进行搜索

python - 存储 MySql 查询结果以便更快地重用

python - 使用 matplotlib 在箱线图中显示传单颜色

python - 使用包含新标签的数据附加带有 MultiIndex 的 pandas DataFrame,但保留旧 MultiIndex 的整数位置

python - 如何使用 geopandas 和 python 连接/合并多个压缩的 shapefile?

python - 使用常规月份顺序而不是字母顺序的交叉表后重新索引列