简体   繁体   English

Python,Pandas:获得列表中第一个None位置的更好方法,它给出了最大的连续无计数

[英]Python, Pandas: A Better way to get the first None position in list which give maximum consecutive None count

I have lists that contain None like the following lists. 我有像以下列表一样包含None的列表。

l1 = [None, 1, None, None, 2, None, None]
l2 = [None, 1, 1, None, None, None, 2, None, None]

I want to get the first None position in this list which gives the maximum consecutive None count. 我希望在此列表中获得第一个None位置,该位置给出最大连续None计数。

get_start_None_pos(l1) # should return 2
get_start_None_pos(l2) # should return 3

My current approach with Pandas which works fine but it too slow when I have so many lists to deal with. 我目前使用Pandas的方法效果很好,但是当我有这么多列表要处理时它太慢了。

def get_start_None_pos(l: list) -> int:
    s = pd.Series(l)
    s = s.isna()
    s = s.cumsum() - s.cumsum().where(~s).ffill().fillna(0)
    return int(s.idxmax() - s.max() + 1)

I would like to know, is there any better way to solve something like this? 我想知道,有没有更好的方法来解决这样的问题?

Here's one with NumPy - 这是NumPy的一个 -

def maxconsecNone_start(l):
    a = np.isnan(np.asarray(l, dtype=np.float64))
    a1 = np.r_[False,a,False]
    idx = np.flatnonzero(a1[:-1] != a1[1:])
    return idx[2*(idx[1::2]-idx[::2]).argmax()]

Sample runs - 样品运行 -

In [49]: l1
Out[49]: [None, 1, None, None, 2, None, None]

In [50]: l2
Out[50]: [None, 1, 1, None, None, None, 2, None, None]

In [51]: maxconsecNone_start(l1)
Out[51]: 2

In [52]: maxconsecNone_start(l2)
Out[52]: 3

itertools.groupby

l=[list(y) for x,y in itertools.groupby(l2)]
x=max([(x,y)for x , y in enumerate(l) if all(v is None for v in y)], key = lambda x: len(x[1]))
sum(list(map(len,l[:x[0]])))
Out[465]: 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果list不是None,则获取list的第一个元素:Python - Get first element of list if list is not None: Python 有没有更好的方法来获取 pandas 中的连续年月值计数? - Is there a better way to get consecutive year-month values count in pandas? Python熊猫适用:第一行没有问题 - Python pandas apply: problem with None in first row Python 函数递归 - 给出“列表”中“数字”第一次出现的索引,如果数字不在列表中,则返回 None - Python Function Recursive - Give Index of first occurence of 'number' in 'list' AND return None if number not in list Python中更好的“如果不是没有返回” - Better “return if not None” in Python 使用 Python 对包含“无”的列表求和 - Sum a list which contains 'None' using Python 有没有比 try except 更好的方法从列表理解中获取 int 结果(当涉及 None 或 empty 时)? - Is there a better way to get an int result out of list comprehension than try except (when None or empty is involved)? 在列表中查找最大值的无意外值 - Python 3递归 - Unexpected Value of None for Finding Maximum in a List - Python 3 Recursion 在python中追加列表,但结果却没有 - appending list in python but get none as a result Python pandas:如何从指定列中选择第一个非“ None”值? - Python pandas: How to select the first not “None” value from a specif column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM