If I have an array: A = np.array([[1,2,0],[5,6,0]])
. How can I replace the third column with the sum of the first two or some other arithmetic combination of the other columns?
In the example, calculating the third column as the sum of the sum of the first 2 would give: np.array([[1,2,3],[5,6,11]])
.
I've tried A[:2] = A[:,0] A[:,1]
and A[:2] = A[:,0].T A[:,1].T
. I've searched for adding columns, but found ways to insert columns.
import numpy as np
A = np.array([[1,2,3],[5,6,7]])
A[:2] = A[:,0] A[:,1]
In R this is very easy, but I don't see a simple way to do it in Python.
CodePudding user response:
You're almost there:
>>> A[:,2] = A[:,0] A[:,1]
>>> A
array([[ 1, 2, 3],
[ 5, 6, 11]])
In A[:, k]
:
A
is the array you're indexing:
as the first index means "all rows"- For instance,
A[:, :]
means "all rows and all columns"
- For instance,
k
as the second index means "k
th column"- For instance,
A[1, 2]
means "element at row 1, column 2" A[2, :]
means "row 2, all its columns"
- For instance,
This can be generalised to any number of dimensions.
CodePudding user response:
slice array and equate to the sum along the row axis.
A[all rows,column 3]
= sum of each row in array A
code below
A[:,2]=A.sum(1)
array([[ 1, 2, 3],
[ 5, 6, 11]])