Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the current row in pandas dataframe during df.iterrows()

Tags:

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!

like image 728
JCm Avatar asked Mar 05 '15 10:03

JCm


People also ask

How do I delete a row in Pandas DataFrame?

To delete a row from a DataFrame, use the drop() method and set the index label as the parameter.

What does DF Iterrows () do?

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).

How do I delete rows in Pandas DataFrame based on condition?

Use pandas. DataFrame. drop() method to delete/remove rows with condition(s).

How do I drop a row using ILOC?

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.


1 Answers

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

like image 174
EdChum Avatar answered Sep 29 '22 20:09

EdChum