I want to substract the two numbers found in each string values from the list array and convert into an integer.
current df:
pbp
0 ['0-0', '0-2', '0-4']
1 ['0-0', '2-0', '4-2']
2 ['0-0', '0-1', '0-2']
expected df:
pbp
0 [0, -2, -4]
1 [0, 2, 2]
2 [0, -1, -2]
tried: df[['pbp']].applymap(lambda x: x.strip()).applymap(ast.literal_eval)
pbp
0 [0-0, 0-2, 0-4]
1 [0-0, 2-0, 4-2]
2 [0-0, 0-1, 0-2]
I just don't know how to substract them
Here's a quick and naive way to achieve what you want:
def subtract_list(my_list):
result=[]
for val in my_list:
numbers = val.split('-')
res = int(numbers[0] )- int(numbers[1])
result.append(res)
print(result)
return result
Calling the method would return:
subtract_list(['0-0', '0-2', '0-4'])
[0, -2, -4]
While not stated in the question this answer can cover multiple math operations using a pattern
and re.split
.
import re
def compute(data):
output = []
for entry in data:
equation = re.split('([\/|\-|\+|\*\*|\*|%])', entry)
result = {
'*' : lambda e: int(e[0]) * int(e[2]),
'+' : lambda e: int(e[0]) + int(e[2]),
'-' : lambda e: int(e[0]) - int(e[2]),
'\/': lambda e: int(e[0]) / int(e[2]),
'%' : lambda e: int(e[0]) % int(e[2]),
}[equation[1]](equation)
output.append(result)
return output
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.