Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting 1 or 0 to new Pandas column conditionally [duplicate]

Tags:

python

pandas

A pretty straightforward pandas question:

If I have a dataframe as such:

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

and I'd like to create a new column 'lunch' that'll have the value 1 if 11<=hour<=1 and 0 otherwise, what's the best and computationally quickest way to do this?

like image 684
SpicyClubSauce Avatar asked Oct 07 '15 05:10

SpicyClubSauce


People also ask

How do I get the value of a column based on another column value?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression.


1 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
like image 56
Zero Avatar answered Sep 24 '22 01:09

Zero