HackleSaw
HackleSaw

Reputation: 139

Adding two columns in pandas with a character between them

I have 7 columns in my csv. I want to join the first two columns and I have done that by converting the csv into dataframe and :

df["patient_week"] = df["Patient"] + df["Weeks"].astype(str)

What this gives me is the values of both columns joined as it should : But I want the values to be joined with a "_" between them. How do I go about this?

Upvotes: 0

Views: 624

Answers (3)

Dishin H Goyani
Dishin H Goyani

Reputation: 7713

You can use DataFrame.agg

df["patient_week"] = df[["Patient","Weeks"]].astype('str').agg('_'.join,axis=1)

Upvotes: 1

AtanuCSE
AtanuCSE

Reputation: 8940

Sample Data:

   col2 col3
id      
1   3   8
2   4   3
3   5   9

Code:

df['New']=df['col2'].astype(str)+"_"+df['col3'].astype(str)
df

Result:

   col2 col3 New
id          
1   3   8   3_8
2   4   3   4_3
3   5   9   5_9

In your case:

df["patient_week"] = df["Patient"] +"_"+ df["Weeks"].astype(str)

Upvotes: 1

Arpit
Arpit

Reputation: 394

Just simply use '_' string between them

Upvotes: 0

Related Questions