Carlo Pazolini
Carlo Pazolini

Reputation: 315

Concatenate two dfs with strings column by column

I have two tables df1 and df2.

print(df1)
    bar1 foo1
0    a   e
1    b   f
2    c   g

print(df2)
    bar2 foo2
0    x   l
1    y   m
2    z   n

I need to concatenate them column by column into one table with two columns.

I need this table:

     bar3  foo3
0    a x   e l
1    b y   f m
2    c z   g n

How can I do it using pandas?

Upvotes: 3

Views: 168

Answers (1)

Vaishali
Vaishali

Reputation: 38415

You can simply add the two data frames with the desired separator,

new_df = df1 + ' ' + df2

    bar   foo
0   a x   e l
1   b y   f m
2   c z   g n

If case the column names of the two dataframes do not match, add the underlying arrays and call DataFrame constructor with desired column names.

pd.DataFrame(df1.values + ' ' + df2.values, columns = ['bar3', 'foo3'])

    bar3    foo3
0   a x     e l
1   b y     f m
2   c z     g n

Upvotes: 4

Related Questions