Reputation:
I am trying to combine two Columns in a df but keep a space between the two values
For the df below I can combine them through the following.
d = ({
'A' : ['Foo','Bar','Foo'],
'B' : ['A','B','C'],
})
df = pd.DataFrame(data=d)
df["Com"] = df["A"].map(str) + df["B"]
Output:
A B Com
0 Foo A FooA
1 Bar B BarB
2 Foo C FooC
But I'd like a space in between. So the intended Output is:
A B Com
0 Foo A Foo A
1 Bar B Bar B
2 Foo C Foo C
Upvotes: 3
Views: 111
Reputation: 3421
I think you can simply get the output by
df['Com']=df['A'] + ' ' + df['B']
python is smart enough.
Upvotes: 1
Reputation: 336
Just use apply function for DataFrame
df['Com'] = df.apply(lambda x: x['A']+' '+x['B'], axis=1)
df
Out[25]:
A B Com
0 Foo A Foo A
1 Bar B Bar B
2 Foo C Foo C
Upvotes: 0
Reputation: 862406
You can add new string with space:
df["Com"] = df["A"].map(str) + ' ' + df["B"]
print (df)
A B Com
0 Foo A Foo A
1 Bar B Bar B
2 Foo C Foo C
Python 3.6 solution:
df["Com"] = [f'{i} {j}' for i, j in zip(df["A"], df["B"])]
print (df)
A B Com
0 Foo A Foo A
1 Bar B Bar B
2 Foo C Foo C
Python 3 solution:
df["Com"] = ['{} {}'.format(i, j) for i, j in zip(df["A"], df["B"])]
Upvotes: 1