2016-01-10 31 views
3

我有一個2維numpy數組,numpy數組中的某處有np.nan值。 現在我試圖旋轉90度的陣列。但是,scipy.ndimage.rotate不起作用。scipy ndimage.rotate不能使用np.nan值

下面是一個簡單的測試:

import numpy as np 
from scipy import ndimage 

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

ndimage.rotate(a, 90) 
# result: 
# array([[2, 4], 
#  [1, 3]]) 

ndimage.rotate(b, 90) 
# result: 
# array([[ nan, nan], 
#  [ nan, nan]]) 

有沒有辦法解決ndimage旋轉的問題呢?

回答

4

scipy.ndimage.rotate實際上是scipy.ndimage.interpolation.rotate,它表示問題:數組中的值被插值,並且用NaN插值任何東西都會導致NaN(同上無窮大)。

顯然,加布裏埃爾建議的rot90只是切換元素,而不需要插值。通用rotate需要插值,因爲例如通過旋轉。 42度不是簡單的元素變化。

總而言之,我會說rotate確實工作與NaN。只是因爲上述原因,不符合你的預期。

+0

很好的解釋爲什麼他們的代碼不工作。 – Gabriel

+1

謝謝@ Gabriel。隨意將它合併到你的答案中,因爲這是OP試圖實現的更直接的解決方案。 – Evert