TransWikia.com

pandas remove for loop

Stack Overflow Asked by arne on December 8, 2020

I have now the following for loop which I want to get rid off, since it’s too slow.

for i in range(len(df)):
    df.loc[i,"date_time"] = datetime.datetime.strptime(str(df.loc[i,"Date"] + ' ' + df.loc[i,"Time"]), '%d-%m-%Y %H:%M:%S')

Input:

index. date        time 
1      10-10-2010  00:00:00
2      10-10-2010  00:00:03
3      10-10-2010  00:00:06
4      10-10-2010  00:00:09

Desired output, with one column with datetime objects:

index. date        time      date_time
1      10-10-2010  00:00:00  10-10-2010  00:00:00
2      10-10-2010  00:00:03  10-10-2010  00:00:00
3      10-10-2010  00:00:06  10-10-2010  00:00:00
4      10-10-2010  00:00:09  10-10-2010  00:00:00

One Answer

Whenever possible, use vector operations instead of loops. Something like this should work (tested on the included sample):

df['date_time'] = pd.to_datetime(df['date'] + ' ' + df['Time'])

Correct answer by Marat on December 8, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP