Python testing true/false condition on data frame column and returning output in new column

dataframe, pandas, python

Solution

If needed convert the 'week' column `datetime` dtype using `to_datetime` then you can just compare the day attribute using `dt.day` and use this as the condition for `np.where`:

In [47]:
df['week'] = pd.to_datetime(df['week'])
df['factor'] = np.where(df['week'].dt.day < 7, 'y', 'x')
df

Out[47]:
        week  day  check factor
0 2017-01-08    8  False      x
1 2017-01-15   15  False      x
2 2017-01-22   22  False      x
3 2017-01-29   29  False      x
4 2017-02-05    5   True      y

Problem

I'm very new to coding in Python so I'm trying to get to grips with some basics - any input is appreciated. I have a list of weekly dates, and am trying to run an 'if' statement on the days, i.e. if the day number is less than 7, create a column with a factor x, or else create a factor y - as in the table below: ``` week day check factor 0 2017-01-08 8 False x 1 2017-01-15 15 False x 2 2017-01-22 22 False x 3 2017-01-29 29 False x 4 2017-02-05 5 True y ``` I tried the code below: ``` if df['day'] <7 : factor=weeks['day']/7 else: .... ``` and got an error: ``` ValueError: The truth value of a Series is ambiguous ``` which I have looked into, and understand that the code above is attempting to test the whole column and hence there can not be an unambiguous true/false response. I have seen some comments about all/any, but these also do not give me the response I'm looking for. Is there a way of testing each item in a column and returning a different output depending on the value?

Original source