how do I use the array first element to do some math in python
Question:
I have an
array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2])
I want to get the sum of the equation:
(5.1 – 1)
(4.9 – 1)
(4.7 – 1)
(4.6 – 1)
How do I get the every arrays’ first element?
Answers:
Assuming this is a Numpy array, you can just subtract from the first column and let broadcasting do the work. If you want the sum of that result, just use sum()
:
import numpy as np
arr = np.array([
[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2]
])
a = arr[:, 0] - 1
#array([4.1, 3.9, 3.7, 3.6])
a.sum()
15.299999999999999
If you are bothered by the inexact sum, make sure you read Is floating point math broken?
There’s an axis
argument in array.sum that you can set to sum the array vertically.
(arr-1).sum(axis=0)
array([15.3, 8.8, 1.6, -3.2])
I have an
array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2])
I want to get the sum of the equation:
(5.1 – 1)
(4.9 – 1)
(4.7 – 1)
(4.6 – 1)
How do I get the every arrays’ first element?
Assuming this is a Numpy array, you can just subtract from the first column and let broadcasting do the work. If you want the sum of that result, just use sum()
:
import numpy as np
arr = np.array([
[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2]
])
a = arr[:, 0] - 1
#array([4.1, 3.9, 3.7, 3.6])
a.sum()
15.299999999999999
If you are bothered by the inexact sum, make sure you read Is floating point math broken?
There’s an axis
argument in array.sum that you can set to sum the array vertically.
(arr-1).sum(axis=0)
array([15.3, 8.8, 1.6, -3.2])