numpy数组元素明智的除法(1/x) [英] Numpy array element-wise division (1/x)
本文介绍了numpy数组元素明智的除法(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
或
np.divide(1.0, array)
它不起作用.
到目前为止,我发现的唯一方法是编写如下内容:
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?
推荐答案
1 / array
进行整数除法并返回array([1, 0, 0, 0])
.
1 / array
makes an integer division and returns array([1, 0, 0, 0])
.
1. / array
会将数组强制转换为float并完成技巧:
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 ])
这篇关于numpy数组元素明智的除法(1/x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文