barciewicz
barciewicz

Reputation: 3793

Create a new column by concatenating two others with string formatting

I have the following code to concatenate two columns into a new one:

import pandas as pd

d = {
    'name': ['Tomek', 'Jacek', 'Placek'],
    'surname': ['A', 'B', 'C'],
}

df = pd.DataFrame(d)
df['fullname'] = df['name'] + ' ' + df['surname']
print(df)

# output:
#    name surname  fullname
# 0   Tomek       A   Tomek A
# 1   Jacek       B   Jacek B
# 2  Placek       C  Placek C

However, I need to use string formatting instead:

import pandas as pd

d = {
    'name': ['Tomek', 'Jacek', 'Placek'],
    'surname': ['A', 'B', 'C'],
}

df = pd.DataFrame(d)
df['fullname'] = f"{df['name']} {df['surname']}"
print(df)

But then the output is:

#     name surname                                           fullname
# 0   Tomek       A  0     Tomek\n1     Jacek\n2    Placek\nName: n...
# 1   Jacek       B  0     Tomek\n1     Jacek\n2    Placek\nName: n...
# 2  Placek       C  0     Tomek\n1     Jacek\n2    Placek\nName: n...

How can I use string formatting and still have the output like the first one?

Upvotes: 3

Views: 1594

Answers (2)

bharatk
bharatk

Reputation: 4315

Try this without list comprehension:

Ex.

import pandas as pd

d = {
    'name': ['Tomek', 'Jacek', 'Placek'],
    'surname': ['A', 'B', 'C'],
}

df = pd.DataFrame(d)
df['fill_name']= df.name.str.cat(df.surname,sep=" ")
print(df)

O/P:

     name surname fill_name
0   Tomek       A   Tomek A
1   Jacek       B   Jacek B
2  Placek       C  Placek C

Upvotes: 1

anky
anky

Reputation: 75100

I need to use string formatting instead

Use zip() and then list comprehension

df['fill_name']=[f"{a} {b}" for a,b in zip(df.name,df.surname)]
print(df)

     name surname fill_name
0   Tomek       A   Tomek A
1   Jacek       B   Jacek B
2  Placek       C  Placek C

Upvotes: 1

Related Questions