我有一个如下所示的 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。 我发现了类似的线程,但没有解决上述问题。 我该如何解决这个问题?预先感谢。
代码
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}