Skip to main content
 首页 » 编程设计

python之使用 Pandas 的 NaN 过滤时间序列中的空洞

2025年05月04日16cmt

我在使用 pandas NA 过滤数据时遇到了一些麻烦。我有一个看起来像这样的数据框:

        Jan       Feb       Mar       Apr       May June 
0  0.349143  0.249041  0.244352       NaN  0.425336  NaN 
1  0.530616  0.816829       NaN  0.212282  0.099364  NaN 
2  0.713001  0.073601  0.242077  0.553908  NaN       NaN 
3  0.245295  0.007016  0.444352  0.515705  0.497119  NaN 
4  0.195662  0.007249       NaN  0.852287  NaN       NaN 

我需要过滤掉有“漏洞”的行。我将行视为时间序列,我所说的空洞是指序列中间的 NA,但不在末尾。 IE。在上面的数据框中,第 0、1 和 4 行有空洞,但第 2 和 3 行没有(仅在行尾有 NA)。

到目前为止我能想到的唯一方法是这样的:

for rowindex, row in df.iterrows(): 
    # now step through each entry in the row  
    # and after encountering the first NA,  
    # check if all subsequent values are NA too. 

但我希望可能有一种更简单、更有效的方法来做到这一点。

谢谢, 安妮

请您参考如下方法:

正如你所说,循环(iterrows)是最后的手段。试试这个,它使用 apply 和 axis=1 而不是遍历行。

In [19]: def holey(s): 
    starts_at = s.notnull().argmax() 
    next_null = s[starts_at:].isnull().argmax() 
    if next_null == 0: 
        return False 
    any_values_left = s[next_null:].notnull().any() 
    return any_values_left 
   ....:  
 
In [20]: df.apply(holey, axis=1) 
Out[20]:  
0     True 
1     True 
2    False 
3    False 
4     True 
dtype: bool 

现在您可以像 df[~df.apply(holey, axis=1)] 那样进行过滤。

这里有一个方便的习惯用法:使用 argmax() 在一系列 bool 值中找到第一次出现的 True。