2

I have a dafatframe such as this:

    A      B   
0  NaN   string1
1  NaN   string2
2  Nan   string1
3  Nan   string1

How can I change all the values in column A such that they are boolean based on whether the entry at same index in column B contains a certain string "stringX"?

2
  • 1
    In this case, if stringX = "string1", then the desired output inside column A is True False True True Commented Aug 14, 2017 at 10:37
  • You are welcome! Commented Aug 14, 2017 at 11:09

1 Answer 1

3

I think you need assign boolean mask, instead == is possible use eq or use assign:

#if need True False values by condition
stringX = "string1"
df['A'] = df['B'] == stringX
print (df)
       A        B
0   True  string1
1  False  string2
2   True  string1
3   True  string1

df['A'] = df['B'].eq(stringX)
print (df)
       A        B
0   True  string1
1  False  string2
2   True  string1
3   True  string1

df = df.assign(A=df['B'].eq(stringX))
print (df)
       A        B
0   True  string1
1  False  string2
2   True  string1
3   True  string1

#if need values of column by condition
df.loc[df['B'] == 'string1', 'A'] = df['B'] 
print (df)
         A        B
0  string1  string1
1      NaN  string2
2  string1  string1
3  string1  string1

#if need scalar by condition
df.loc[df['B'] == 'string1', 'A'] = 1
print (df)
     A        B
0    1  string1
1  NaN  string2
2    1  string1
3    1  string1

#if need if else condition with 2 scalars
df['A'] = np.where(df['B'] == 'string1', 1, 2)
print (df)
   A        B
0  1  string1
1  2  string2
2  1  string1
3  1  string1
Sign up to request clarification or add additional context in comments.

Comments

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.