简体   繁体   中英

How to set the value of a pandas dataframe column with an operation over the same column

I am trying to execute the following sentence in a python script over a Pandas dataframe:

boxes_df["delivery_date"] = (dateutil.parser.parse(boxes_df["delivery_date"]) + datetime.timedelta(weeks=weeks_before)).strftime("%Y-%m-%d")

But I'm getting this error:

TypeError: Parser must be a string or character stream, not Series

How can I make the such a calculation?

You may want

df["delivery_date"] = (df["delivery_date"].apply(dateutil.parser.parse) + datetime.timedelta(weeks=weeks_before)).dt.strftime("%Y-%m-%d")

But more pandas way is

df["delivery_date"] = (pd.to_datetime(df["delivery_date"]) + pd.Timedelta(weeks=weeks_before)).dt.strftime("%Y-%m-%d")

.dt.strftime("%Y-%m-%d") can be replace by .dt.date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM