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.
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.
Concatenating string with non-string columns In this case, you can simply cast the column using pandas. DataFrame. astype() or map() methods.
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.
df['bar'] = df.bar.map(str) + " is " + df.foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With