如何更改订单列并将它们组合在一个pandas数据框中?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何更改订单列并将它们组合在一个pandas数据框中?相关的知识,希望对你有一定的参考价值。

我下面有两个熊猫数据框。如何更改列的顺序并将它们组合起来?谢谢!

+-----+---------------+-----------------+
| Id  |     Name      |      Title      |
+-----+---------------+-----------------+
| 121 | Value 2       | This is a title |
| 323 | Is a row with | Only one cell   |
+-----+---------------+-----------------+


+-----+---------------+--------+
| Id  |     Title     |  Name  |
+-----+---------------+--------+
| 443 | Title again   | Henk   |
| 454 | Just a Titile | Hertog |
+-----+---------------+--------+

我想要一个像下面的列;)

+-----+-----------------+----------------+
| Id  |      Title      |      Name      |
+-----+-----------------+----------------+
| 121 | This is a title | Value 2        |
| 323 | Only one cell   | Is a row with  |
| 443 | Title again     | Henk           |
| 454 | Just a Titile   | Hertog         |
+-----+-----------------+----------------+
答案

使用函数concat,它也正确对齐列名称并通过list更改列的顺序:

cols = ['Id', 'Title', 'Name']
df = pd.concat([df1, df2], ignore_index=True, sort=False)[cols]
print (df)
    Id            Title           Name
0  121  This is a title        Value 2
1  323    Only one cell  Is a row with
2  443       Title gain           Henk
3  454    Just a Titile         Hertog

或者首先更改排序,然后使用concat

df = pd.concat([df1[cols], df2[cols]], ignore_index=True, sort=False)
另一答案

你也可以尝试:

df = df[['Id', 'Title', 'Name']]

简单而简单的索引/选择。

以上是关于如何更改订单列并将它们组合在一个pandas数据框中?的主要内容,如果未能解决你的问题,请参考以下文章