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

标签 python pandas dataframe

我在下面得到了两个 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/

相关文章:

java - 将 Java 转换为 Python - 属性值转换为字符串

python - 使用 Peewee 追溯创建索引?

Python Pandas - 合并 CSV 并添加文件名

python - 重新采样 Pandas 列日期时间

r - 为什么在使用 pivot_wider 时会产生 NA 值?

python - 将多条推文放入数据框中

python - 如何在pygame中用颜色填充我的图形?

python - 没有创建它应该创建的 csv 文件

python - pandas - 转换数据 View

python - pandas 滚动对象如何工作?