0

I am having issues trying to modify a value if columnA contains lets say 0,2,12,44,75,81 (looking at 33 different numerical values in columnA. If columnA contains 1 of the 33 vaules defined, i need to then change the same row of colulmnB to "approved".

I have tried this: df[(df.columnA == '0|2|12|44|75|81')][df.columnB] = 'approved'

I get an error that there are none of index are in the columns but, i know that isn't correct looking at my csv file data. I must be searching wrong or using the wrong syntax.

1
  • the | separated string you've made implements or logic when used for regex searches with str.contains; the equality requires it to be exactly that string with all the letters and vertical bars in that exact order. Instead, I'm guessing you want to create a list of your values and use .isin: stackoverflow.com/questions/19960077/… Commented Mar 8, 2021 at 22:20

1 Answer 1

2

As others have said, if you need the value in column A to match exactly with a value in the list, then you can use .isin. If you need a partial match, then you can convert to string dtypes and use .contains.

setup:

nums_to_match = [0,2,9]
df
   A  B
0  6  e
1  1  f
2  3  b
3  6  g
4  6  i
5  0  f
6  9  a
7  6  i
8  6  a
9  2  h

Exact match:

df.loc[df.A.isin(nums_to_match),'B']='approved'
df:
   A         B
0  6         e
1  1         f
2  3         b
3  6         g
4  6         i
5  0  approved
6  9  approved
7  6         i
8  6         a
9  2  approved

partial match:

nums_to_match_str = list(map(str,nums_to_match))
df['A']=df['A'].astype(str)
df.loc[df.A.str.contains('|'.join(nums_to_match_str),case=False,na=False),'B']='approved'
df
   A         B
0  1         h
1  4         c
2  6         i
3  7         d
4  3         d
5  9  approved
6  5         i
7  1         c
8  0  approved
9  5         d
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly. Thank you for the additional context and options as well to help understand better.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.