[英]How to loop through each row in pandas dataframe and set values equal to nan after a threshold is surpassed?
[英]How to set equal to nan after first grouping of values above threshold in numpy array?
如果我有一個像這樣的numpy數組:
np.array([-9, -8, -9, -7, -7, -4, -4, -2, -3, -4, -4, -8, -4, -2, -8, -2])
閾值為-4
如何找到大於-5的第一個值分組,然后將第一個分組后的所有值設置為等於np.nan,這樣我就得到了這樣的數組:
np.array([-9, -8, -9, -7, -7, -4, -4, -2, -3, -4, -4, np.nan, np.nan, np.nan, np.nan, np.nan])
遍歷該數組,一次取5,即每i取i到i + 5。 檢查每個條件(循環或通過方法調用),以及是否錯誤地移動到下一個條件。 一旦成立,請中斷循環並記錄分組結束的i的值。 將i + 1作為新循環的起始索引,然后將i + 1設置為數組末尾為nan。
我不知道Nan
所以我用了零。 如果數組很大,請嘗試不使用for循環的類似方法。 解決方案取決於輸入數組的可變性,因此請檢查它是否應為<
, >
或更確切地說>=
, <=
。 這可以給出一個主意(?):
更新 :由於這里的評論改進的建議:
A = np.array([-9, -8, -9, -7, -7, -4, -4, -2, -3, -4, -4, -8, -4, -2, -8, -2])
val = -5
ind1 = (A > val).argmax()
ind2 = (A[ind1:]<val).argmax()
A[ind1+ind2:] = 0
A
array([-9, -8, -9, -7, -7, -4, -4, -2, -3, -4, -4, 0, 0, 0, 0, 0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.