-1

I have the following code which I would like to convert into a single line I guess using list comprehension? But I have been unsuccessful in converting it.

exp_days = ["16/04/2021","23/04/2021","27/04/2021"]

for i in range(len(df)):
    if df["Date"][i] in exp_days:
        list_of_days.append(1)
    else:
        list_of_days.append(0)

My dataframe:

Date
16/04/2021
19/04/2021
20/04/2021
21/04/2021
22/04/2021
23/04/2021
26/04/2021
27/04/2021

Expected output:

list_of_days = [1,0,0,0,0,1,0,1]
horcrux
  • 6,493
  • 6
  • 27
  • 40
JPWilson
  • 539
  • 2
  • 10

2 Answers2

2
list_of_days = [ 1 if df["Date"][i] in exp_days else 0 for i in range(len(df)) ]
horcrux
  • 6,493
  • 6
  • 27
  • 40
1

Alternative via numpy -

exp_days = ["16/04/2021","23/04/2021","27/04/2021"]
import numpy as np
result = np.where(df['Date'].isin(exp_days),1,0)

Nk03
  • 14,136
  • 2
  • 6
  • 20