我有一个包含 np.nan(Numpy非数字)值的Pandas数据框:
field1
2020-12-24 NaN
2020-12-25 NaN
2020-12-26 1.0
2020-12-27 2.0
2020-12-28 NaN
2020-12-29 1.0
2020-12-30 2.0
(该索引是日期时间。)我想获得一个新的数据框,其中包括起始日期和np.nan出现的次数,即:
field1
2020-12-24 2
2020-12-28 1
我已经尝试了这段代码:
prev = 1
for col_name, el in df.iterrows():
print(el)
if prev != np.nan and el[0] == np.nan:
cnt = 1
if prev == np.nan and el[0] == np.nan:
cnt = cnt + 1
if prev == np.nan and el[0] != np.nan:
print(cnt)
prev = el[0]
但它并不像预期的那样工作,而且我希望避免使用“for”循环,因为我预计在更大的数据框上速度会非常慢。任何帮助将不胜感激!