Home > database >  How to add in front of positive integers before string concatenation?
How to add in front of positive integers before string concatenation?

Time:02-18

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:

    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().

CodePudding user response:

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)

CodePudding user response:

That should do the trick:

zed['c'] = zed['a'].apply(lambda x: '{: }'.format(x))   ' '   zed['b'].apply(lambda x: '{: }'.format(x))

Python >= 3.6

As @Tomerikoo suggested the code can be simplified using f-String:

zed['c'] = zed['a'].apply(lambda x: f'{x: }')   ' '   zed['b'].apply(lambda x: f'{x: }')
  • Related