Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add + in front of positive integers before string concatenation?

I have this code:

import pandas as pd

zed = pd.DataFrame(data = {'a': [3, -5], 'b': [-4, 7]})
zed['c'] = zed['a'].astype(str) + ' ' + zed['b'].astype(str)

Which gives:

    a   b   c
0   3   -4  3 -4
1   -5  7   -5 7

But I am looking for column c to be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    a   b   c
0   3   -4  +3 -4
1   -5  7   -5 +7

i.e. the positive numbers should have a + prefix.

my code gets messy very quickly when I add if/else conditionals everywhere. I have created the following function:

def plus_prefix(a):
    if a > 0:
        b = '+' + a.astype(str)
    else:
        b = a.astype(str)
    return b

but zed['c'] = plus_prefix(zed['a']) + ' ' + plus_prefix(zed['b']) throws an error The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). How can this be improved? Would be great if I could create plus_prefix so that it can be chained at the end, zed['a'].plus_prefix().

>Solution :

You can use the apply() method to apply a function onto a DataFrame (see documentation):

zed['c'] = zed['a'].apply(plus_prefix) + ' ' + zed['b'].apply(plus_prefix)

However, since your values are integers, I got a new error since it doesn’t know astype(). After modifying your function, I was able to get it to work:

import pandas as pd

def plus_prefix(a):
    if a > 0:
        b = '+' + str(a)
    else:
        b = str(a)
    return b

zed = pd.DataFrame(data = {'a': [3, -5], 'b': [-4, 7]})
zed['c'] = zed['a'].apply(plus_prefix) + ' ' + zed['b'].apply(plus_prefix)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading