[SOLVED] How to compare two columns and input the smaller one in a new column in pandas?


I am working on a DataFrame that looks like this. I’d like to choose the faster date of the two and put it into another column.

col1 col2 col3
2015-01-03 2015-01-04
2022-02-22 2017-01-02

and my desired out put is

col1 col2 col3
2015-01-03 2015-01-04 2015-01-03
2022-02-22 2017-01-02 2017-01-02

So far I’ve tried

for i in range(len(df)):
    if df.loc[i, "col1"] < df.loc[i, "col2"]:
        df.loc[i, "col3"] = df.loc[i, "col1"]
        df.loc[i, "col3"] = df.loc[i, "col2"]


You could use min on axis:

df['col3'] = df[['col1','col2']].min(axis=1)


         col1        col2        col3
0  2015-01-03  2015-01-04  2015-01-03
1  2022-02-22  2017-01-02  2017-01-02

Answered By – enke

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *