Python中仅对最后n行执行Dropna操作

3

我正在尝试清理数据集。 在最后3行中,如果列“B”为空,则删除整个行。 我还没有想出如何仅在特定行上使用dropna。

   A   B 
1  1   3
2  5
3  6   5 
4  2
5  3   6

需要成为

   A   B 
1  1   3
2  5
3  6   5 
5  3   6
1个回答

2
你需要将最后三行切片,然后应用你的条件,并将其传递给 drop
n=3
df=df.drop(df.tail(n).B.eq('').loc[lambda x : x].index)
   A  B
1  1  3
2  5   
3  6  5
5  3  6

谢谢,太好了。实际上我不得不使用df=df.drop(df.tail(n).B.isnull().loc[lambda x : x].index),因为我的值是“None”,但是没错,那是正确的。 - Vedran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接