Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy array element-wise division (1/x)

My question is very simple, suppose that I have an array like

array = np.array([1, 2, 3, 4])

and I'd like to get an array like

[1, 0.5, 0.3333333, 0.25]

However, if you write something like

1/array

or

np.divide(1.0, array)

it won't work.

The only way I've found so far is to write something like:

print np.divide(np.ones_like(array)*1.0, array)

But I'm absolutely certains that there is a better way to do that. Does anyone have any idea?

like image 380
Roophie Avatar asked Apr 30 '12 13:04

Roophie


People also ask

How do you use element-wise division in NumPy?

divide(arr1, arr2, out = None, where = True, casting = 'same_kind', order = 'K', dtype = None) : Array element from first array is divided by elements from second element (all happens element-wise). Both arr1 and arr2 must have same shape and element in arr2 must not be zero; otherwise it will raise an error.

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])

How do you divide elements in an array?

Examples : Input : a[] = {5, 100, 8}, b[] = {2, 3} Output : 0 16 1 Explanation : Size of a[] is 3. Size of b[] is 2. Now 5 has to be divided by the elements of array b[] i.e. 5 is divided by 2, then the quotient obtained is divided by 3 and the floor value of this is calculated.

How do you divide a NumPy array into equal parts?

Splitting NumPy Arrays Splitting is reverse operation of Joining. Joining merges multiple arrays into one and Splitting breaks one array into multiple. We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.


2 Answers

1 / array makes an integer division and returns array([1, 0, 0, 0]).

1. / array will cast the array to float and do the trick:

>>> array = np.array([1, 2, 3, 4])
>>> 1. / array
array([ 1.        ,  0.5       ,  0.33333333,  0.25      ])
like image 171
eumiro Avatar answered Oct 01 '22 18:10

eumiro


I tried :

inverse=1./array

and that seemed to work... The reason

1/array

doesn't work is because your array is integers and 1/<array_of_integers> does integer division.

like image 39
mgilson Avatar answered Oct 01 '22 19:10

mgilson