I have a data frame representing the schedule of some restaurants in a week.
- What i want to do is to add a column
is_OpenSaturday
to my initial Dataframedf
that represents If the restaurant is open on Saturdays (boolean value: 0 or 1)
note : the value 0
or 0:0-0:0
simply means that the restaurant is closed that day.
data = {
'restaurant_id': ['1', '2','3'],
'Monday': ['11:0-20:0', '11:30-22:0','11:30-21:0'],
'Tuesday': ['11:0-20:0', '11:30-22:0','11:30-22:0'],
'Wednesday': ['11:0-20:0', '11:30-22:0','11:30-21:0'],
'Thursday': ['11:0-20:0', '11:30-22:0','11:30-21:0'],
'Friday': ['11:0-22:0', '11:30-22:0','11:30-21:0'],
'Saturday': ['11:0-22:0', '0:0-0:0',0],
'Sunday': ['11:0-17:0', '16:30-21:30','11:30-21:0',],
}
df = pd.DataFrame (data, columns = ['restaurant_id','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday',])
What could be a simple syntax to achieve this?
(One of) the (syntactically) simplest way is to apply a
lambda
function on elements of theSaturday
column:Output:
The lambda function says that if its string value is '0:0-0:0' or '0', then the restaurant is closed (return 0). Otherwise it is open (return 1).
Note that one must use
df["is_OpenSaturday"] =
but notdf.is_OpenSaturday =
on the left hand side. Theis_OpenSaturday
column will be created automatically only using the[]
operator.Also note that, efficiency-wise,
.apply()
is the last option you would like to try. Alist(map())
construct is better in general if you have a lot of data. The equivalent syntax is shown as follows.