suppose i have
JavaScript
x
2
1
list1 = [3, 4, 6, 8, 13]
2
in a for loop I want to subtract the value i from the value that comes right after. In the above example: 4-3, 6-4, 8-6, 13-8. (and i want to skip the first value) desired result
JavaScript
1
2
1
list2 = [3, 1, 2, 2, 5]
2
can i do this in a for loop / list comprehension?
more specifically do I want to do this in a dataframe
JavaScript
1
8
1
2
list1
3
0 3
4
1 4
5
2 6
6
3 8
7
4 13
8
and after the operation
JavaScript
1
8
1
list1 list2
2
0 3 3
3
1 4 1
4
2 6 2
5
3 8 2
6
4 13 5
7
8
I have tried for loops, lambda functions and list comprehensions and trying to access the positional index with enumerate() but I can’t figure out how to access the value just before the value from which I want to subtract from
edit: answers below worked. thank you very much!
Advertisement
Answer
You should use shift
to access the next row:
JavaScript
1
2
1
df['list2'] = df['list1'].sub(df['list1'].shift(fill_value=0))
2
JavaScript
1
2
1
df['list2'] = df['list1'].diff().fillna(df['list1'])
2
Output:
JavaScript
1
7
1
list1 list2
2
0 3 3
3
1 4 1
4
2 6 2
5
3 8 2
6
4 13 5
7
For a pure python solution:
JavaScript
1
4
1
list1 = [3, 4, 6, 8, 13]
2
3
list2 = [a-b for a,b in zip(list1, [0]+list1)]
4
Output: [3, 1, 2, 2, 5]