Reputation: 3
I have an N x N Numpy array. I need to manipulate the ith column in a paricular way, and the remaining columns in a different but common way. How do i do this in a numpythonic manner. The parameter i is passed to the function to be used.
Example:
a=np.zeros([4,4])
Now, we need 1st,2nd and 4th, say to be squared element wise. 3rd one to be cubed elementwise.
Upvotes: 0
Views: 1276
Reputation: 1117
Since raising 0s to any power is still 0, let's use 2s.
import numpy as np
a = np.full((4, 4), 2.0)
a[:, 2] = a[:, 2]**3
ci = [i for i in range(a.shape[1]) if i != 2]
a[:, ci] = a[:, ci]**2
Upvotes: 0
Reputation: 5031
You can use a set of numbers to select the columns you want to manipulate. For example you could say:
a[:,(0,1,3)] = a[:,(0,1,3)]**2
to square column 1, 2, and 4. Remember they are indexed from zero.
More generally if you only want to manipulate all but column X
, then you could
sel = range(a.shape[1])
sel.remove(X)
a[:, sel] = a[:, sel]**2
Upvotes: 0
Reputation: 280456
most_of_the_result = do_whatever(numpy.delete(arr, col_index, axis=1))
insertion_column = do_other_thing(arr[:, col_index])
result = numpy.insert(most_of_the_result, col_index, insertion_column, axis=1)
or
result = do_whatever(arr)
special_column = do_other_thing(arr[:, col_index])
result[:, col_index] = special_column
Upvotes: 1