1

I have a dataframe:

Color   Name    Age   City   Value
Blue    Bob     28    Atl    0
Green   Bob     27    Chi    0
Blue    Sam     28    Atl    0

I have the above DF and I want all values to equal 1 if the color is blue, age is 28 and city is Atl.

I tried using df.loc but I got an error that says 'too many indexers'

0

3 Answers 3

1

This will work

df.loc[(df.Color=='Blue')&(df.Age==28)&(df.City=='Atl'),'Value']=1
df
Out[687]: 
   Color Name  Age City  Value
0   Blue  Bob   28  Atl      1
1  Green  Bob   27  Chi      0
2   Blue  Sam   28  Atl      1
Sign up to request clarification or add additional context in comments.

Comments

1

For these problems, I usually default to np.select, so that I can create complex conditions, and set the outputs in a clear and expandable way.

First, create your conditions (Create as many of these as you want):

p1 = df.Color.eq('Blue')
p2 = df.Age.eq(28)
p3 = df.City.eq('Atl')

condition = p1 & p2 & p3

Now using numpy.select, passing a list of your conditions, a list of your matching outputs, and a default value:

df.assign(Value=np.select([condition], [1], df.Value))

   Color Name  Age City  Value
0   Blue  Bob   28  Atl      1
1  Green  Bob   27  Chi      0
2   Blue  Sam   28  Atl      1

If you really only have one condition, you can also use numpy.where here:

np.where(condition, 1, df.Value)
# array([1, 0, 1], dtype=int64)

Comments

0

You can use np.where with multiple conditional statements. If you have the original dataframe you can execute the following code

import numpy as np
df['value'] = np.where((df['Color'] == 'Blue') & (df['Age'] == 28) & (df['City'] == 'Atl'), 1, 0)

to yield

Color  Name  Age  City  Value
Blue   Bob   28   Atl     1
Green  Bob   27   Chi     0
Blue   Sam   28   Atl     1

Obviously, you can change the conditions as needed/wanted or even create additional columns using the same technique.

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.