我有一个如下所示的数据框。有 >=1 个连续行,其中 y_l 被填充,y_h 为 NaN,反之亦然。 当 NaN 之间有超过 1 条连续填充的行时,我们只想保留 y_l 最低或 y_h 最高的行。 例如在下面最后 3 行的 df 中,我们只保留第二行并丢弃其他两行。 实现这一目标的明智方法是什么?
df = pd.DataFrame({'y_l': [NaN, 97,95,98,NaN],'y_h': [90, NaN,NaN,NaN,95]}, columns=['y_l','y_h'])
>>> df
y_l y_h
0 NaN 90.0
1 97.0 NaN
2 95.0 NaN
3 98.0 NaN
4 NaN 95
期望的结果:
y_l y_h
0 NaN 90.0
1 95.0 NaN
2 NaN 95
最佳答案
您需要创建新列或系列
来区分每个连续项,然后使用groupby
聚合 agg
,最后更改列的顺序使用 reindex
:
a = df['y_l'].isnull()
b = a.ne(a.shift()).cumsum()
df = (df.groupby(b, as_index=False)
.agg({'y_l':'min', 'y_h':'max'})
.reindex(columns=['y_l','y_h']))
print (df)
y_l y_h
0 NaN 90.0
1 95.0 NaN
2 NaN 95.0
详细信息:
print (b)
0 1
1 2
2 2
3 2
4 3
Name: y_h, dtype: int32
关于python - 如何过滤 pandas 数据框中的 NaN 行的连续数据行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46876504/