r/learnpython • u/thing_42 • Jul 30 '25
Trying to understand Df.drop(index)
This is my code:
For index, row in df.iterrows(): If (condition): df.drop(index)
What am I missing? I ran the code, yes the if statement is 'True', I checked that. I expect the row at that index to disappear and it's still there.
0
Upvotes
View all comments
Show parent comment
2
u/Muted_Ad6114 Jul 31 '25
Yes you can do it with one line. These are all without loops. Pandas is optimized for vectorized operations. You are basically creating boolean filter [true, false, true, true, etc] and using that array to mask the dataframe. I don’t know what your data looks like or what comparison you actually want to make but could do something like this for multiple collumns:
Try seeing what each part does on its own.
This should create an array of boolean values. Where it is True if the signal is sell and False otherwise.
This creates another array where it is True if the price is greater than sell and false otherwise for every row.
Then we get the boolean AND value of combining them with & which is just another boolean array.
Finally we use that array to mask the df. Which should return a a smaller df with only the rows you want. You can also invert the array using the NOT operator ~.