【问题标题】:Return indexes of longest batches of NaN返回最长批次 NaN 的索引
【发布时间】:2020-08-28 01:09:17
【问题描述】:

我有一个按两列排序的数据框:“ID”和一个日期列。
该表中有大量缺失值,我感兴趣的是了解缺失值是如何分布的:它们是否主要集中在一个“ID”上,例如,所有 ID 的开头是否都有缺失值(日期明智),缺失值是不相关的等等。

在 groupby ID + 缺失值计数之后,我使用了 missingno 包,它被证明是有用的,这是我得到的结果(清理列名):

从图片中,似乎有特定批次的行缺少大多数列。 例如,如果您查看箭头,我可能会为要搜索的索引设置一个值 (~idx = 750000),但这并不实用,因为还有其他实例发生了同样的事情。
我想要的是一个函数batches_missing(cols, n_rows),它接受一个列列表和一个int n_rows,并返回给定列具有的所有批次的元组列表[(index_start_batch1, index_end_batch1), ...]超过 n_rows 个连续的缺失值行。

有一个模拟示例:

df = pd.DataFrame({'col1':[1, 2, np.nan, np.nan, np.nan, np.nan, 2, 2, np.nan, np.nan, np.nan], 
                   'col2':[9, 7, np.nan, np.nan, np.nan, np.nan, 0, np.nan, np.nan, np.nan, np.nan], 
                   'col3':[11, 12, 13, np.nan, 1, 2, 3, np.nan, 1, 2, 3]})

batches_missing(['col1','col2'] , 3) 将返回 [(2,5),(8,10)]

考虑到实际数据非常大(1 百万行),这是否可以有效地完成?我也非常有兴趣了解其他分析缺失数据的方法,因此不胜感激任何阅读材料/链接!

谢谢大家。

【问题讨论】:

  • 通过添加一个最小的可重现示例并解释说我也有兴趣讨论除了简单的计数/百分比之外还有其他潜在的方法来探索缺失数据。

标签: python pandas dataframe missing-data


【解决方案1】:

在给定选定列的情况下,您可以明智地计算行以查看哪些行都是 NA:

rowwise_tally = df[['col1','col2']].isna().apply(all,axis=1)

0     False
1     False
2      True
3      True
4      True
5      True
6     False
7     False
8      True
9      True
10     True

现在您可以对这些运行进行分组:

grp = rowwise_tally.diff().cumsum().fillna(0)
0     0.0
1     0.0
2     1.0
3     1.0
4     1.0
5     1.0
6     2.0
7     2.0
8     3.0
9     3.0
10    3.0

然后统计每组的nas个数,也得到开始和结束:

na_counts = rowwise_tally.groupby(grp).sum()
pos = pd.Series(np.arange(len(df))).groupby(grp).agg([np.min, np.max])
pos[na_counts>=3].to_numpy()

array([[ 2,  5],
       [ 8, 10]])

可能有更好的方法来获得位置,而不是像我一样使用 pd.Series。现在,将其包装成一个函数:

def fun(data,cols,minlen):
    rowwise_tally = data[cols].isna().apply(all,axis=1)
    grp = rowwise_tally.diff().cumsum().fillna(0)
    na_counts = rowwise_tally.groupby(grp).sum()
    pos = pd.Series(np.arange(len(data))).groupby(grp).agg([np.min, np.max])
    return pos[na_counts>=minlen].to_numpy()

fun(df,['col1','col2'],3)

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 2022-01-09
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2017-08-18
    • 2018-02-09
    相关资源
    最近更新 更多