0

I have a list that contains counts for different items as strings. Sometimes a restock is given in brackets. The list looks like this:

23
21 (+3)
32 (+14)

So there is always a space between the number and the brackets. To start of I've wrote a function that I apply over the Series. I've used the split-method two times to return only the first number:

splitted = item.split(" ")
splitted2 = splitted[0].split("+")
return int(splitted2[0])

This solution is kind of hacky already and on top of that, I am missing the restocks in brackets. Now I want to know, how I would possibly add both of the numbers together. I would therefore split the list one time so that I get this as a result:

['23']
['21', '(+3)']

Then I want to select only the list items, that have to values, get rid of the + and () and add the first and the second value together. How would I do that?

Shahriar
  • 13,460
  • 8
  • 78
  • 95
Lennart Thamm
  • 269
  • 1
  • 12
  • 1
    I get contradictory information - is it a list containing strings or a pandas dataframe? The example again looks rather like a text file. – Mr. T Feb 11 '18 at 17:46
  • 1
    What's the desired output for the same list you provided? Is it something like `[23, 24, 56]`, where all the values are integers? – pault Feb 11 '18 at 17:47
  • The desired output are the sums as integers. 24 instead of 21 (+3). Sorry for the confusion: Right now I have the data in a pandas Series within a larger dataframe, but as strings. I'd convert it to whatever format needed to accomplish the desired effect. – Lennart Thamm Feb 11 '18 at 19:37
  • @LennartThamm, did one of the below solutions solve your problem? If so, feel free to accept (tick on left), so other users know. – jpp Feb 14 '18 at 13:24
  • @ jp_data_analysis: Thanks for the insight. And thanks a lot for you help. – Lennart Thamm Feb 16 '18 at 14:49

3 Answers3

3

With help of this question Extract numbers from a string

str = "32 (+14)"
import re
data = re.findall(r'\d+', str)
# ['32', '14']
sum = 0
for d in data:
  sum+=int(d) 

print(sum)

Output:

46

See how numbers are parsed using regex. Here, d represents [0-9]

Another method: (with help of this answer)

>>> import re
>>> str = "32 (+14)"
>>> eval(re.sub('[\(\)]', '', str.replace(' ', '')))
46

This will also allow user to do any operation

Shahriar
  • 13,460
  • 8
  • 78
  • 95
3

This is one way, which literally evaluates the '+' operation.

import ast, re

lst  = ['23', '21 (+3)', '32 (+14)']

lst = [ast.literal_eval(re.sub('[\(\)]', '', i.replace(' ', ''))) for i in lst]

# [23, 24, 46]
jpp
  • 159,742
  • 34
  • 281
  • 339
1

not the best method, but this works. regex will be better option.

>>> str = "32 (+14)"
>>> str.replace("(+", "").replace(")", "").split(" ")
['32', '14']

Regex:

>>> import re
>>> str = "32 (+14)"
>>> nums = re.findall('\d+', str )
>>> print(sum(int(i) for i in nums))
46
Raj Kumar
  • 783
  • 1
  • 8
  • 23