'If with number range

I work with python. I am trying to create a column of ones and zeros, yo know the period of the year.

  • For weeks [25:47], i want to put 0
  • For weeks [48:24], i want to put 1
selected['Period']=np.zeros(len(selected.index))
for i in selected['Week']:
    if (25<=i<=47):
        selected['Period']=0
    elif (48<=i>=24):
        selected['Period']=1

Week columns has week values of the year (int) created from x.week function (from datetime) I have tried to expand the condictions, try differetns forms, but it only takes zero value and i can't see the problem. Thanks!

My idea is to have a column with binary values, and, with a function select the period of the year to work with, or [25,47] period, or [48,24]

To be more clear: [0,24] -> 1 ; [25,47] -> 0 ; [48,52] -> 1.

EDIT: data frame for the loop

output of a part of the data frame



Solution 1:[1]

selected['Period'] = np.zeros(len(selected.index))
for i in selected['Week']:
    if 0 <=i <= 24:
        selected['Period'] = 1
    elif 25 <=i <= 47:
        selected['Period'] = 0
    elif 48 <=i <= 52:
        selected['Period'] = 1

After some time discussing this in the comments, I assume this is what you want.

Solution 2:[2]

What about using a simple else?

selected['Period'] = np.zeros(len(selected.index))
for i in selected['Week']:
    if 25 <=i <= 47:
        selected['Period'] = 0
    else:
        selected['Period'] = 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Josip Juros
Solution 2 Matthias