Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Combining Two DataFrames Horizontally [duplicate]

I have two Pandas DataFrames, each with different columns. I want to basically glue them together horizontally (they each have the same number of rows so this shouldn't be an issue).

There must be a simple way of doing this but I've gone through the docs and concat isn't what I'm looking for (I don't think).

Any ideas?

Thanks!

like image 369
anon_swe Avatar asked Jun 23 '17 14:06

anon_swe


People also ask

How do you horizontally concatenate in Python?

hstack() function. The hstack() function is used to stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.

Which of the following is used to append one or more DataFrames sideways?

Pandas concat() function This function is used to append one (or more) DataFrames stacked below the other (or sideways, depending on whether the axis option is set to 0 or 1).

How do I merge two DataFrames by rows in pandas?

The concat() function in pandas is used to append either columns or rows from one DataFrame to another. The concat() function does all the heavy lifting of performing concatenation operations along an axis while performing optional set logic (union or intersection) of the indexes (if any) on the other axes.

How do I merge two DataFrames in pandas without duplicates?

To concatenate DataFrames, use the concat() method, but to ignore duplicates, use the drop_duplicates() method.


1 Answers

concat is indeed what you're looking for, you just have to pass it a different value for the "axis" argument than the default. Code sample below:

import pandas as pd

df1 = pd.DataFrame({
    'A': [1,2,3,4,5],
    'B': [1,2,3,4,5]
})

df2 = pd.DataFrame({
    'C': [1,2,3,4,5],
    'D': [1,2,3,4,5]
})

df_concat = pd.concat([df1, df2], axis=1)

print(df_concat)

With the result being:

   A  B  C  D
0  1  1  1  1
1  2  2  2  2
2  3  3  3  3
3  4  4  4  4
4  5  5  5  5
like image 133
nslamberth Avatar answered Oct 21 '22 04:10

nslamberth