optimize python code snippet

Asked

Viewed 50 times

0

I’m starting in the world of Python, I wrote the excerpt below and wanted your help to make it more efficient:

dforigin = pd.read_csv(client_file_name.csv, sep=';')

total_line_number = len(dforigin.index)

for i, row in dforigin.iterrows(): 
     dforigin.Dia.loc[i] = datetime.strftime(datetime.strptime(dforigin.Dia[i], 
'%Y-%m-%d'), '%Y%m%d')

This excerpt was only created because I wanted to change the date format on dateframe.

1 answer

1

The column Dia is in the format '%Y-%m-%d'. The first step is to transform to the date type:

dforigin.Dia =  pd.to_datetime(dforigin.Dia, format='%Y-%m-%d')

And then format the way you want:

dforigin.Dia = dforigin.Dia.dt.strftime('%Y%m%d')

Putting it all together in one command we have:

dforigin.Dia =  pd.to_datetime(dforigin.Dia, format='%Y-%m-%d').dt.strftime('%Y%m%d')
  • Noooossa, what a difference!!! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.