Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation of two pandas columns

I have a following DataFrame:

from pandas import * df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]}) 

It looks like this:

    bar foo 0    1   a 1    2   b 2    3   c 

Now I want to have something like:

     bar 0    1 is a 1    2 is b 2    3 is c 

How can I achieve this? I tried the following:

df['foo'] = '%s is %s' % (df['bar'], df['foo']) 

but it gives me a wrong result:

>>>print df.ix[0]  bar                                                    a foo    0    a 1    b 2    c Name: bar is 0    1 1    2 2 Name: 0 

Sorry for a dumb question, but this one pandas: combine two columns in a DataFrame wasn't helpful for me.

like image 691
nat Avatar asked Aug 08 '12 05:08

nat


People also ask

How do I concatenate two strings in a DataFrame in Python?

Pandas str.cat() is used to concatenate strings to the passed caller series of string. Distinct values from a different series can be passed but the length of both the series has to be same. . str has to be prefixed to differentiate it from the Python's default method.

Which option can be used to concatenate 2 columns in pandas if one of them is not string type?

Concatenating string with non-string columns In this case, you can simply cast the column using pandas. DataFrame. astype() or map() methods.

How do you append two columns in Python?

We can use the concat function in pandas to append either columns or rows from one DataFrame to another. Let's grab two subsets of our data to see how this works. When we concatenate DataFrames, we need to specify the axis. axis=0 tells pandas to stack the second DataFrame UNDER the first one.


1 Answers

df['bar'] = df.bar.map(str) + " is " + df.foo 
like image 175
BrenBarn Avatar answered Oct 22 '22 04:10

BrenBarn