简体   繁体   中英

Pandas: Drop a row if it contains a condition

I have a large dataframe and I need to exclude some rows containing a value that is a confound for me.

I have in mind a if statement nested in a for loop like this

for x in range (6655):
test = pseudoF2['Match'][x]

if test[:2].lower() == 'ab':
    pseudoF2.drop(test, inplace=True)

the problem is that I am constantly getting a key error "not found in axis"

just to have an idea, my dataframe is something like this:

Word    Match   Value1  Value2
1   Ab-art  Un-ans  1.95    0.15
2   Ab-art  An-ans  1.95    0.15
3   Ab-art  Um-ans  1.90    0.10
4   Ab-art  Tu-ort  2.15    0.35
5   Ab-drift    An-klift    2.90    0.25
(...)

Thank you for your help.

You can try regular expression to check whether there is ab in Match column, then you can drop those indices

As suggested by Jezreal more elegant solution

df[~df['Match'].str.contains(r'(?i)^ab')]

Old solution

df.drop(df[df['Match'].str.contains(r'(?i)^ab')].index, inplace=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM