Question:
Adding a new column based on the result of another column

Problem:

I have a "Date" column & "Time" column.


I want to create a new column "Tradedate" & depending on the following condition:


If "Time" = 23:00:00, then add one day to "Date" and return result in "Tradedate" column, otherwise return "Date" result in the "Tradedate" column


import pandas as pd

import datetime as dt

df = pd.DataFrame({"Date": ["2021/01/01","2021/01/01","2021/01/02"], "Time": ["22:00:00","23:00:00","00:00:00"]})


df["Date"] = pd.to_datetime(df["Date"])


df.info()


def trade_date(convert):

    

    for x in convert:

        if x == "23:00:00":

            return df["Date"] + pd.DateOffset(days=1)

        else: 

            return df["Date"] 

 

#df["Tradedate"] = df["Time"].apply(trade_date)


df["Tradedate"] = trade_date(df["Time"])

           

#trade_date(df["Time"])


Why doesn't my function work? I instead get just the initial date as opposed to date +1 when time = 23:00:00


Solution:

Please simplify the code like below. I hope it works as u want.


Code:

df["Date"] = pd.to_datetime(df["Date"])

def trade_date(row):

    if row["Time"] == "23:00:00":

        return (row["Date"] + pd.DateOffset(days=1)).strftime('%Y/%m/%d')

    else:

        return row["Date"].strftime('%Y/%m/%d')

df["Tradedate"] = df.apply(trade_date, axis=1)

df["Date"] = df["Date"].dt.strftime('%Y/%m/%d')

print(df)


Output:

        Date      Time   Tradedate

0  2021/01/01  22:00:00  2021/01/01

1  2021/01/01  23:00:00  2021/01/02

2  2021/01/02  00:00:00  2021/01/02


Suggested blogs:

>How to route between different components in React.js?

>How to save python yaml and load a nested class?-Python

>How to send multiple HTML form fields to PHP arrays via Ajax?

>What is data binding in Angular?

>What is microservice architecture, and why is it better than monolithic architecture?

>What is pipe in Angular?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation


Ritu Singh

Ritu Singh

Submit
0 Answers