Home > Back-end >  If with number range
If with number range

Time:03-17

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related