Why can't I use (if x==a : x=b) to replace the value of x

Viewed 38

I want to create a df column where each row has the value 1 if the date is a Sunday, and 0 otherwise. I am able to create a column with values 0-6 using .dt.dayofweek, but cannot work out how to change this column to the format I want it in.

df['X2'] = df.index #the df index is the date
X2 = df['X2'].dt.dayofweek

for x in X2:
    if x==6:
        x=1
    else:
        x=0

This code does nothing to change X2. X2 looks like this before and after the for loop:

Date
2021-09-01    2
2021-09-02    3
2021-09-03    4
2021-09-04    5
2021-09-05    6
             ..
2022-08-27    5
2022-08-28    6
2022-08-29    0
2022-08-30    1
2022-08-31    2
Name: X2, Length: 365, dtype: int64

I want it so that X2 comes out like this:

Date
2021-09-01    0
2021-09-02    0
2021-09-03    0
2021-09-04    0
2021-09-05    1
             ..
2022-08-27    0
2022-08-28    1
2022-08-29    0
2022-08-30    0
2022-08-31    0
etc.
1 Answers

This should work :

df['X2'] = df.index #the df index is the date
X2 = df['X2'].dt.dayofweek
X2 = (X2 == 6).astype('int')
Related