-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]
logi-kal
  • 7,107
  • 6
  • 31
  • 43
JPWilson
  • 691
  • 4
  • 14

2 Answers2

2
list_of_days = [ 1 if df["Date"][i] in exp_days else 0 for i in range(len(df)) ]
logi-kal
  • 7,107
  • 6
  • 31
  • 43
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,699
  • 2
  • 8
  • 22