0

I have a dataframe, df, where I would like to combine a start and end column into one single date column.

start             end              id

10/01/2020        11/01/2020       a

Desired output

Date id

10/01/2020 to 11/01/2020           a

OR

 Date                            id

10/01/2020  11/01/2020            a

This is what I am doing

df1 = df['Date'] = df['start'] + "To " + df['end']


df11.info()
1   start  188 non-null    datetime64[ns]
2   end    188 non-null    datetime64[ns]

I am still researching this, I think I may need to do a conversion to Datetime, however, I see that both of the columns I wish to combine already has a datetime type. Any suggestion is appreciated.

1 Answer 1

1
df['Date']= df.apply(lambda x: x['start'] + ' '+'to'+ ' '+x['end'],1)

Or

df['Date']=df.groupby(df.index).apply(lambda x:x['start'].str.cat(x['end'], sep=' to '))



 start         end id                      Date
0  10/01/2020  11/01/2020  a  10/01/2020 to 11/01/2020
Sign up to request clarification or add additional context in comments.

7 Comments

ok thank you I will try, and to add the new column name, would I just do: df['NewColumn']=df.apply(lambda x: x['start'] + ' '+'to'+ ' '+x['end'],1)
Yes, jus df['Date']=df.groupby(df.index).apply(lambda x:x['start'].str.cat(x['end'], sep=' to '))
I am getting the error: unsupported operand type(s) for +: 'Timestamp' and 'str', yet both column names start and end are datetime64.
Ok, just dtypes issues. You need to convert your dates to str
Please try df.apply(lambda x: x['start'].strftime('%Y-%m-%d') + ' '+'to'+ ' '+x['end'].strftime('%Y-%m-%d'),1)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.