Home > Net >  Create a dataframe column conditional to the Datetime column
Create a dataframe column conditional to the Datetime column

Time:11-03

Imagine I have the following dataframe:

pd.DataFrame({"Date":["10/29/2022", "10/30/2022", "11/5/2022", "11/6/2022"],
      "Values":[1, 6, 8, 12]})

I would like to create a new column with a value that equals to 0 if the row has a date before today and 1 to a date that's still on the future.

Any ideas on how to implement it?

CodePudding user response:

Use:

df['new'] = (pd.to_datetime(df['Date'], dayfirst=False) # convert to datetime
             .gt(pd.Timestamp('today')) # is the date after today?
             .astype(int)  # result as 0/1
            )

Output:

         Date  Values  new
0  10/29/2022       1    0
1  10/30/2022       6    0
2   11/5/2022       8    1
3   11/6/2022      12    1

CodePudding user response:

Try:

df["new"] = (pd.to_datetime(df["Date"]) > pd.Timestamp.now()).astype(int)
print(df)

Prints:

         Date  Values  new
0  10/29/2022       1    0
1  10/30/2022       6    0
2   11/5/2022       8    1
3   11/6/2022      12    1
  • Related