如何在pandas数据帧的列中找到连续的空值(NaN)?

问题描述 投票:0回答:1

我有一个如下所示的 pandas 数据框:

|col1|  |col2|  |col3|  |col4|
| 1  |  |  1 |  | NaN|  | 1  |
|NaN |  |  1 |  | 0  |  | 0  |
|NaN |  | NaN|  | NaN|  | 0  |
|NaN |  |  1 |  | 1  |  | 1  |
|NaN |  |  0 |  | 0  |  | 0  |
| 1  |  |  0 |  | NaN|  | 1  |
|NaN |  |  1 |  | NaN|  | 1  |
|NaN |  |  0 |  | NaN|  | 1  |

我想计算每列的连续空值(NaN)值的数量,如果有两个以上连续空值,我想获得它的最大值。

对于上面的 df,我会得到:

df_nulls = ['col1': 4, 'col2': 0, 'col3': 3, 'col4': 0]

根据上述结果,应该删除连续两个以上空值的列。在这种情况下,最终的数据帧应仅包含 col2 和 col4。 我发现了类似的线程,但没有解决上述问题。 我该如何解决这个问题?预先感谢。

python pandas dataframe numpy count
1个回答
0
投票

代码

out = (df
       .transform(lambda x: x.isna().groupby(x.notna().cumsum()).cumsum())
       .max().mask(lambda x: x.eq(1), 0).to_dict()
)

{'col1': 4, 'col2': 0, 'col3': 3, 'col4': 0}
© www.soinside.com 2019 - 2024. All rights reserved.