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

Time:12-27

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:

CodePudding user response:

use following code

df["Dt-1"] = df[['Dt-1', 'Dt-2']].max(axis=1)

CodePudding user response:

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"]
  • Related