如何获得 Pandas 系列的 NaN 索引范围?

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

我在 Pandas 中有一个数据框,其中索引是日期,列是代码,如下所示:

我需要识别具有 NaN 值的列,我是这样实现这部分的:

boundaries_with_incomplete_days = boundaries.columns[
            boundaries.isna().any()
        ].to_list()

因此,boundaries_with_incomplete_days 是一个列表,其中包含代码(包含 NaN 值的列)。问题是现在我需要确定存在 NaN 值的日期范围。例如,对于 frt00338: 从 2024-01-03 2:00:00 到 2024-01-03 8:00:00, 从 2024-01-07 2:00:00 到 2024-01-07 12:00:00 我得到这个的方式是无关紧要的,它可能是一个元组列表,例如:

[("2024-01-03 2:00:00", "2024-01-03 8:00:00"), ("2024-01-07 2:00:00", "2024-01-07 12 :00:00")]

我的想法是迭代boundary_with_incomplete_days,并确定每个代码的这些范围,但是我不确定如何有效地找到这些范围,我不想遍历每个代码的所有数据。我怎样才能实现它?

python pandas dataframe
1个回答
0
投票

您可以使用:

out = {}
for col in boundaries.columns[boundaries.isna().any()]:
    m = boundaries[col].notna() 
    g = m.cumsum().mask(m)
    r = df.index.to_series().groupby(g).agg(['min', 'max']).astype(str)
    out[col] = list(zip(*r.to_dict('list').values()))

输出:

>>> out
{'frt00338': [('2024-01-03 02:00:00', '2024-01-03 08:00:00'),
  ('2024-01-07 02:00:00', '2024-01-07 12:00:00')]}
© www.soinside.com 2019 - 2024. All rights reserved.