Home > Back-end >  List comprehension to find if it's weekend on dataframe
List comprehension to find if it's weekend on dataframe

Time:01-11

I'm trying to write as list comprehension the following code:

is_weekend = list()
for i in df['date']:
 if i.weekday() > 4:
   is_weekend.append(1)
 else:
   is_weekend.append(0)

I've already tried

is_weekend = [i == 1 for i in df['date'] if i.weekday() > 4 else i == 0]

But it throws invalid syntax errors.

Could you help?

CodePudding user response:

This is the correct way:

is_weekend = [1 if i.weekday() > 4 else 0 for i in df['date']]

CodePudding user response:

This will cast the boolean into 1 or 0 but it is iterative

is_weekend = [int(i.weekday() > 4) for i in df['date']]

A better way would be to use a lambda with apply on the date column and convert the resulting series into list using the tolist method.

is_weekend = df['date'].apply(lambda i: 1 if i.weekday() > 4 else 0).tolist()
  •  Tags:  
  • Related