I would like to delete the current row during iteration - using df.iterrows()
, if it its certain column fails on my if
condition.
ex.
for index, row in df: if row['A'] == 0: #remove/drop this row from the df del df[index] #I tried this but it gives me an error
This might be a very easy one, but i still can't figure out how to do it. Your help will be very much appreciated!
To delete a row from a DataFrame, use the drop() method and set the index label as the parameter.
Pandas DataFrame iterrows() Method The iterrows() method generates an iterator object of the DataFrame, allowing us to iterate each row in the DataFrame. Each iteration produces an index object and a row object (a Pandas Series object).
Use pandas. DataFrame. drop() method to delete/remove rows with condition(s).
Use iloc to get the row as a Series, then get the row's index as the 'name' attribute of the Series. Then use the index to drop.
I don't know if this is pseudo code or not but you can't delete a row like this, you can drop
it:
In [425]: df = pd.DataFrame({'a':np.random.randn(5), 'b':np.random.randn(5)}) df Out[425]: a b 0 -1.348112 0.583603 1 0.174836 1.211774 2 -2.054173 0.148201 3 -0.589193 -0.369813 4 -1.156423 -0.967516 In [426]: for index, row in df.iterrows(): if row['a'] > 0: df.drop(index, inplace=True) In [427]: df Out[427]: a b 0 -1.348112 0.583603 2 -2.054173 0.148201 3 -0.589193 -0.369813 4 -1.156423 -0.967516
if you just want to filter those rows out you can perform boolean indexing:
df[df['a'] <=0]
would achieve the same thing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With