'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:
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 1:[1]
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:+}')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
