Search code examples
pythonpandasnumpywhere-clauseassign

Where Column item is equal to specific value insert new item


I am trying to insert a new Column based off values in a separate Column. For the df below I have a Column of days. Where the value in this Column is equal to Monday, I want to insert a 0 into a new Column called Group.

Here is my attempt:

import pandas as pd
import numpy as np

d = ({             
   'Day' : ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],                                                                                                                                                 
    })

df = pd.DataFrame(data=d)

df['Group'] = np.where(df['Day'] == 'Monday', 0)
print(df)

Error:

ValueError: either both or neither of x and y should be given


Solution

  • You need to provide a value for both when the day is and isn't Monday. If you take a look at docs, that's what is referred to as x and y. Right now you only provide something for the former. So let's say all non-Mondays go to group 1, then you have:

    df['Group'] = np.where(df['Day'] == 'Monday', 0, 1)