Concatenating DataFrames horizontally in Pandas
Start your free 7-days trial now!
Solution
To concatenate DataFrames horizontally in Pandas, use the concat(~) method with axis=1.
Example
Case when index matches
To combine horizontally two DataFrames df1 and df2 with matching index:
Note that for two DataFrames to be concatenated horizontally perfectly like above, we need their index to match exactly. In this case, df1 and df2 both have a matching index of [0,1,2].
Case when index does not match
To combine horizontally two DataFrames df1 and df2 that have non-matching index:
Notice how we end up with some missing values. This happens because the concat(~) method concatenates rows based on matching index values.
To perfectly concatenate horizontally even when the index does not match, use the DataFrame's reset_index(~) method to first convert the index of the DataFrames to the default integers:
import pandas as pd
df_concat
A B0 1 41 2 52 3 6
Here, the drop=True argument for reset_index(~) is necessary because this method attaches the index of the DataFrame to its column by default - the drop=True prevents this behaviour. Just for your reference, here is the result of df1.reset_index(drop=True):
A B0 1 41 2 52 3 6