danielssl
danielssl

Reputation: 29

Create a dataframe column conditional to the Datetime column

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?

Upvotes: 1

Views: 31

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195603

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

Upvotes: 0

mozway
mozway

Reputation: 262359

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

Upvotes: 1

Related Questions