Setting 1 or 0 to a new Pandas column conditionally

Pretty simple pandas question:

If I have a data frame as such:

   hour
 0  0
 1  1
 2  1
 3  2
 4  2
  ...

and I would like to create a new “lunch” column that will have a value of 1 if 11 <= hour <= 1 and 0 otherwise, what is the best and fastest way to do this?

+4
source share
3 answers

You could

In [231]: df['lunch'] = (df['hour']<=11) & (df['hour']<=1)

In [232]: df['lunch']
Out[232]:
0     True
1     True
2     True
3    False
4    False
Name: lunch, dtype: bool

In [233]: df['lunch'].astype(int)
Out[233]:
0    1
1    1
2    1
3    0
4    0
Name: lunch, dtype: int32
+4
source

You can have a vector approach (the minus operator is used here to negate the Boolean mask):

df['lunch'] = (-df.hour.isin(range(2,11))).astype(int)

Out[368]:
   hour  lunch
0     0      1
1     1      1
2     1      1
3     2      0
4     2      0
+6
source

Try:

>>> df['lunch']=df['hour'].apply(lambda x: 1 if x >= 11 or x <= 1 else 0)
>>> df
   hour  lunch
0     0      1
1     1      1
2     1      1
3     2      0
4     2      0
+2
source

Source: https://habr.com/ru/post/1610530/


All Articles