如何根据上面的行删除行?蟒蛇 pandas [英] How to delete row based on row above? Python Pandas
本文介绍了如何根据上面的行删除行?蟒蛇 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的数据集:
I have a dataset which looks like this:
df = pd.DataFrame({'a': [1,1,1, 2, 3, 3, 4], 'b': [1,np.nan, np.nan, 2, 3, np.nan, 4]})
我正在寻找删除本质上在下一行中具有np.nan的所有行.我不知道如何执行此操作,因为我不知道如何基于其他行删除行.
I'm looking to delete all rows which have np.nan in the next proceeding row essentially. I can't figure out how to do this because I don't know how to delete rows based on other rows.
推荐答案
您要查找下一行所有具有np.nan的行.为此使用shift:
You want to find all the rows that have a np.nan in the next row. Use shift for that:
df.shift().isnull()
a b
0 True True
1 False False
2 False True
3 False True
4 False False
5 False False
6 False True
然后,您要弄清楚该行中是否有任何内容,因此您希望将其简化为单个布尔掩码.
Then you want to figure out if anything in that row was nan, so you want to reduce this to a single boolean mask.
df.shift().isnull().any(axis=1)
0 True
1 False
2 True
3 True
4 False
5 False
6 True
dtype: bool
然后只需删除列:
df.drop(df.shift().isnull().any(axis=1))
a b
2 1 NaN
3 2 2
4 3 3
5 3 NaN
6 4 4
这篇关于如何根据上面的行删除行?蟒蛇 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文