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

I would like to delete the current line during iteration - using df.iterrows() if this is its some column failing in my if state.

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 

It may be very simple, but I still cannot figure out how to do it. Your help will be greatly appreciated!

+6
source share
1 answer

I do not know if this is pseudo-code or not, but you cannot delete such a line, you can drop it:

 In [425]: df = pd.DataFrame({'a':np.random.randn(5), 'b':np.random.randn(5)}) df Out[425]: ab 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]: ab 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 these lines, you can do boolean indexing:

 df[df['a'] <=0] 

achieve the same

+10
source

Source: https://habr.com/ru/post/983367/


All Articles