Reputation: 89
For example, say I have:
a = np.array([[1, 2, 3, 6], [2, 45, 34, 56],[3, 8, 56, 45]])
I want to subtract 1 from the first number in all the rows. So it prints:
array([[0, 2, 3, 6], [1, 45, 34, 56],[2, 8, 56, 45]])
I have tried doing
a = np.array([[1, 2, 3, 6], [2, 45, 34, 56],[3, 8, 56, 45]]) -1
but, it subtracts from all the numbers rather than just the first one.
Upvotes: 2
Views: 2795
Reputation: 2424
Just for the sake of completeness:
your numpy 2D array looks like this:
[[ 1 2 3 6]
[ 2 45 34 56]
[ 3 8 56 45]]
what you want to do is subtract 1 from the first column.
This can be done by slicing the entire first column and subtracting 1 from its items.
in numpy you can slice columns like array[:,col_num]
or rows like array[row_num,:]
where the :
means the all the rows
or all the columns
respectively.
so your solution is:
a[:,0] -=1
where you select all items of row with index 0 and subtract 1 from them.
I highly recommend you follow the basic and intermediate python tutorials of this link as they will make you familiar with these concepts and many others.
Hope this was helpful.
Upvotes: 1
Reputation: 5231
I believe what you are looking for is:
a[:,0]-=1
[:,0]
will access all values along the first axis, with the zeroth index along the second axis.
Upvotes: 6