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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With