Pythonic way to determine whether not null list entries are 'continuous'

后端 未结 11 1219
渐次进展
渐次进展 2021-02-01 01:35

I\'m looking for a way to easily determine if all not None items in a list occur in a single continuous slice. I\'ll use integers as examples of not None items

11条回答
  •  臣服心动
    2021-02-01 02:11

    Here's a way just using numpy :

    a = np.array([1, 2, 3, np.nan, 4, 5, np.nan, 6, 7])
    
    # This returns indices of nans
    # eg. [[3], [6]]
    # use .squeeze() to convert to [3, 6]
    aa = np.argwhere(a != a).squeeze()
    
    # use a diff on your array , if the nans
    # are continuous, the diff will always be 1
    # if not, diff will be > 1 , and using any() will return True
    any(np.diff(aa) > 1) 
    

提交回复
热议问题