Skip to content
Advertisement

LOC search string with AND condition in Python

I’m trying to use LOC with an AND condition. It works fine with OR conditions, but I can’t get it to work with ANDs when there are duplicate values in a column.

JavaScript

This table with no duplicates works as expected:

JavaScript

But when you create a data frame with two “granny” entries the double replace AND condition replaces both instances of “granny” even though “apple” in the AND condition isn’t being matched.

JavaScript

No doubt my fault, and a misplacing of brackets (or misunderstanding of code), but what is the correct way to achieve an AND condition replace with loc (or other easier method)?

Current output:

JavaScript

Desired output:

JavaScript

Advertisement

Answer

The issue is in the else block in locreplace

JavaScript

Which is a list with a series in the first index rather than a series. You need to remove the brackets and replace and with &

JavaScript

Output

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement