0

Right now, I have a DF like this

Words               Words1
Little Red         Red Apple
Cracker Barrel     Wood Grain
Far Away Man       Flat Rate Shipping

I want to remove cells from my DF based on a particular condition where certain words cannot appear together in the same phrase.

So for example: Remove cells from the following DF where "Flat" is in the same phrase as "Shipping" AND where "Far" is in the same phrase as "Man". I've been playing around with something like this but it doesn't work...

Words.where(Words.applymap(lambda x: 'Flat' and 'Shipping' in x))

Any ideas?

1 Answer 1

1

What do you mean by "remove cells"? I think you mean remove rows right? Then this will be an apply since you'll consider things rowwise.

In [8]: def pred(x):
    c1 = ('Far' in x[0]) and ('Man' in x[0])
    c2 = ('Flat' in x[1]) and ('Shipping' in x[1])
   ...:     return c1 and c2

In [9]: df.apply(pred, axis=1)
Out[9]: 
0    False
1    False
2     True
dtype: bool

So you can drop those rows that match your criteria with

In [10]: df[~df.apply(pred, axis=1)]
Out[10]: 
            Words      Words1
0      Little Red   Red Apple
1  Cracker Barrel  Wood Grain

It may be quicker to use the str.match method with a regex.

3
  • Unfortunately, I'm using Pandas and using this method throws the following error: IndexError: ('index out of bounds', 'occurred at index 0') Sep 29, 2014 at 21:11
  • Figured out why it was throwing that error -- unfortunately this doesn't work for me Sep 29, 2014 at 21:25
  • DF = DF.applymap(lambda x: x if not '$' in str(x) else x.replace('$', '')) or DF = DF.applymap(lambda x: x if not '%' in str(x) else x.replace('%', '')) Feb 23, 2017 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.