[英]Changing the array value above the first non-zero element in the column
正如您寫的關於數組(不是DataFrame ),我假設您有一個Numpy數組並且想要使用Numpy方法。
要完成您的任務,請運行以下代碼:
np.where(np.cumsum(np.not_equal(array, 0), axis=0), array, 255)
步驟示例及說明:
源數組:
array([[0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 0]])
np.not_equal(array, 0)
計算一個 boolean 數組,元素為True := 0:
array([[False, True, False], [False, False, True], [ True, True, False], [ True, False, False]])
np.cumsum(..., axis=0)
) 沿軸0 (列)計算累積和( True計為1 ):
array([[0, 1, 0], [0, 1, 1], [1, 2, 1], [2, 2, 1]], dtype=int32)
4. 上面的數組是where 中使用的掩碼。 對於掩碼值(其中掩碼的對應元素為True (實際上, != 0 )),從數組的對應元素中取值,否則取255 :
np.where(..., array, 255)
結果(對於我的數組)是:
array([[255, 1, 255],
[255, 0, 1],
[ 1, 1, 0],
[ 1, 0, 0]])
使用遮罩:
array[array == 0] = 255
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.