我在下面得到了两个 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)
关于python - 如何更改订单列并将它们组合在一个 Pandas 数据框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55826359/