Concatenate values of 2 columns into 1 (equivalent of R's paste)
<p>Example data in python 3.5:</p>

<pre><code>import pandas as pd
df=pd.DataFrame({"A":["x","y","z","t","f"],
                "B":[1,2,1,2,4]})
</code></pre>

<p>This gives me a dataframe with 2 columns "A" and "B".
I then want to add a third column "C" that contains the value of "A" and "B" concatenated and separated by "_".<br>
Following the suggestion from <a href="http://stackoverflow.com/questions/28046408/equivalent-of-rs-paste-command-for-vector-of-numbers-in-python?rq=1">this answer</a> I can do it like this.</p>

<pre><code>for i in range(0,len(df["A"])):
    df.loc[i,"C"]=df.loc[i,"A"]+"_"+str(df.loc[i,"B"]) 
</code></pre>

<p>I get the result I want but it seems convoluted for such a simple task.</p>

<p>In R this would be done like this:</p>

<pre><code>df&lt;-data.frame(A=c("x","y","z","t","f"),
               B=c(1,2,1,2,4))
df$C&lt;-paste(df$A,df$B,sep="_")
</code></pre>

<p>Another <a href="http://stackoverflow.com/questions/21292552/equivalent-of-paste-r-to-python">thread</a> suggested the use of the "%" operator but I can't get it to work.</p>

<p>Is there a better alternative?</p>

<p>You can just add the columns together but for 'B' you need to cast the type using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype(str)</code></a>:</p>

<pre><code>In [115]:
df['C'] = df['A'] + '_' + df['B'].astype(str)
df

Out[115]:
   A  B    C
0  x  1  x_1
1  y  2  y_2
2  z  1  z_1
3  t  2  t_2
4  f  4  f_4
</code></pre>

<p>This is a vectorised approach and will scale much better than looping over every row for large dfs</p>

python pandas