Comparing datetime64[ns] colmns in a pandas dataframe in lambda seems to be not working

Question:

What i want to acheive is to change date-time value in Dt-1 with Dt-2 if Dt-1 is grater than Dt-2.
I am using lambda function with if-else pattern to compare colums but, Dt-1 value is changed if the condition is not met. Any help is appriciated.Thank you.

Bellow is my short code sample , and output when run :

     import pandas as pd

df = pd.DataFrame([["a", "2022-11-01 00:01:11", "2022-11-02 00:02:33"]
                   ],
                  columns=["gr", "Dt-1", "Dt-2"])

df["Dt-1"] = pd.to_datetime(df["Dt-1"])
df["Dt-2"] = pd.to_datetime(df["Dt-2"])

print(df)
print(df.info())

df["Dt-1"] = df.apply(lambda x: x["Dt-1"] if x["Dt-1"] >
                      x["Dt-2"] else x["Dt-2"], axis=1)

print(df)
print(df.info())

Program output:

Asked By: Facimus

||

Answers:

Sorry for posting this , if-else works correct… my bad sorry… 🙂

lambda x: x["Dt-1"] if x["Dt-1"] > x["Dt-2"] else x["Dt-2"]
Answered By: Facimus

use following code

df["Dt-1"] = df[['Dt-1', 'Dt-2']].max(axis=1)
Answered By: Panda Kim
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.