我在下面得到了两个熊猫数据框。 如何更改列的顺序并合并它们? 谢谢!
+-----+---------------+-----------------+
| 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 |
+-----+-----------------+----------------+
答案 0 :(得分:3)
使用功能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)
答案 1 :(得分:1)
您也可以尝试:
df = df[['Id', 'Title', 'Name']]
轻松简单的索引编制/选择。