【发布时间】:2022-01-09 12:26:25
【问题描述】:
我有一个像这样的二维数组 numpy :
s = np.array([[ 5., 4., np.nan, 1., np.nan],
[np.nan, 4., 4., 2., 2.],
[ 3., np.nan, np.nan, 5., 5.],
[np.nan, 3., 4., 4., np.nan]])
#now i want to create a new np array s1 base on s like this
s1= np.empty((len(s),len(s)))
for i in range(len(s)):
a = np.abs(s - s[i])
a = np.nanmean(a, axis=1)
w = 1 / (a + 0.001)
s1[i] = w
s1
array([[1000. , 1.99600798, 0.33322226, 0.49975012],
[ 1.99600798, 1000. , 0.33322226, 0.999001 ],
[ 0.33322226, 0.33322226, 1000. , 0.999001 ],
[ 0.49975012, 0.999001 , 0.999001 , 1000. ]])
#without use for loop i write like this
def f(x,y):
a = np.abs(s[y]-s[x])
a = np.nanmean(a)
if np.isnan(a):
return 0
w = 1/(a+0.001) #not let 1/0
return w
s1 = np.fromfunction(np.vectorize(f),(len(s),len(s)),dtype='int')
s1
array([[1000. , 1.99600798, 0.33322226, 0.49975012],
[ 1.99600798, 1000. , 0.33322226, 0.999001 ],
[ 0.33322226, 0.33322226, 1000. , 0.999001 ],
[ 0.49975012, 0.999001 , 0.999001 , 1000. ]])
首先我想问的是我的 np.fromfunction 对吗? 其次,有没有其他方法可以用numpy重写这段代码而不使用for循环?
【问题讨论】: