Ron
Ron

Reputation: 75

How to assign a new value to a column with "OR" in Python

I have the follwoing dataframe called Grades:

    Name    Grade
0   Ron     100
1   Dana    69
2   Bob     77
3   Dan     32
4   John    99
5   Brita   115

I want to create a new column (called "Love") and in this new column to assign a boolean of value "true" to the rows of "Dana" and "John" - since they are the two people which I love. So the outcome should be:

    Name    Grade  LOVE
0   Ron    100      False
1   Dana    69      True
2   Bob     77      False
3   Dan     32      False
4   John    99      True
5   Brita   115     False

I tried this code but it did not work:

Grades['Love'] = Grades.Name == ('Marie' | 'John')

How to use the "Or" assignment correctly?

Upvotes: 0

Views: 116

Answers (3)

Sergei Lazarevich
Sergei Lazarevich

Reputation: 101

You could try something like this:

Grades['Love'] = Grades.Name.isin(['Dana', 'John'])

Here is the result:

    Name    Grade   Love
0   Ron     100     False
1   Dana    69      True
2   Bob     77      False
3   Dan     32      False
4   John    99      True
5   Brita   115     False

Upvotes: 3

imxitiz
imxitiz

Reputation: 3987

You may try this :

>>> Grades["Love"]=Grades["Name"].str.contains("Dana|John")
>>> Grades
    Name  Grade   Love
0    Ron    100  False
1   Dana     69   True
2    Bob     77  False
3    Dan     32  False
4   John     99   True
5  Brita    115  False

As you said Grades is DataFrame. For more information about str.contains() you may visit here.

Upvotes: 2

ThePyGuy
ThePyGuy

Reputation: 18426

You can use isin, to check for multiple values

>>> df.assign(LOVE=df['Name'].isin(['Dana',  'John']))

    Name  Grade   LOVE
0    Ron    100  False
1   Dana     69   True
2    Bob     77  False
3    Dan     32  False
4   John     99   True
5  Brita    115  False

If you want to use OR, you need to combine the series of truthfulness for each individual values by OR i.e. |:

>>> df.assign(LOVE=(df['Name']=='Dana')|(df['Name']=='John'))

    Name  Grade   LOVE
0    Ron    100  False
1   Dana     69   True
2    Bob     77  False
3    Dan     32  False
4   John     99   True
5  Brita    115  False

Upvotes: 2

Related Questions