Suppose I have a numpy array:
1 10
2 20
3 0
4 30
and I want to add a third column where each row is the sum (or some arbitrary calculation) of the first two columns in that row:
1 10 11
2 20 22
3 0 3
4 30 34
How do I do that?
For these kinds of calculations the built-in map function is very useful. It only remains to add the result of the calculation to the third column. For summing:
>>> import numpy as np
>>> my_arr = np.array([[1, 10], [2, 20], [3, 0], [4, 30]])
>>> np.vstack( (my_arr.T, map(sum, my_arr) )).T
array([[ 1, 10, 11],
[ 2, 20, 22],
[ 3, 0, 3],
[ 4, 30, 34]])
It also works with other functions:
>>> my_func = lambda x: 2*x[0] + x[1]
>>> np.vstack( (my_arr.T, map(my_func, my_arr) )).T
array([[ 1, 10, 12],
[ 2, 20, 24],
[ 3, 0, 6],
[ 4, 30, 38]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With