Aercheon
Aercheon

Reputation: 113

How to change order columns and combine them together in a single pandas dataframe?

I got two pandas data frames below. How can I change the order of the columns and combine them? Thanks!

+-----+---------------+-----------------+
| 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 |
+-----+---------------+--------+

I want a column like below ;)

+-----+-----------------+----------------+
| 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         |
+-----+-----------------+----------------+

Upvotes: 1

Views: 44

Answers (2)

jezrael
jezrael

Reputation: 862661

Use function concat, it correct align columns names also and change order of columns by 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

Or first change ordering and then use concat:

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

Upvotes: 3

Rajat Jain
Rajat Jain

Reputation: 2032

You can also try:

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

Easy and simple indexing/selection.

Upvotes: 1

Related Questions