Home > database >  Changing date column of csv with Python Pandas
Changing date column of csv with Python Pandas

Time:06-01

I have a csv file like this:

Tarih, Şimdi, Açılış, Yüksek, Düşük, Hac., Fark %
31.05.2022, 8,28, 8,25, 8,38, 8,23, 108,84M, 0,61%

(more than a thousand lines)

I want to change it like this:

Tarih, Şimdi, Açılış, Yüksek, Düşük, Hac., Fark %
5/31/2022, 8.28, 8.25, 8.38, 8.23, 108.84M, 0.61%

Especially "Date" format is Day.Month.Year and I need to put it in Month/Day/Year format.

i write the code like this:

import pandas as pd
import numpy as np
import datetime

data=pd.read_csv("qwe.csv", encoding= 'utf-8')

df.Tarih=df.Tarih.str.replace(".","/")
df.Şimdi=df.Şimdi.str.replace(",",".")
df.Açılış=df.Açılış.str.replace(",",".")
df.Yüksek=df.Yüksek.str.replace(",",".")
df.Düşük=df.Düşük.str.replace(",",".")

for i in df['Tarih']:
    q = 1
    datetime_obj = datetime.datetime.strptime(i, "%d/%m/%Y")
    df['Tarih'].loc[df['Tarih'].values == q] = datetime_obj

But the "for" loop in my code doesn't work. I need help on this. Thank you

CodePudding user response:

have you tried using datetime Object? reference

CodePudding user response:

Just looking at converting the date, you can import to a datetime object with arguments for pd.read_csv, then convert to your desired format by applying strftime to each entry.

If I have the following tmp.csv:

date, value
30.05.2022, 4.2
31.05.2022, 42
01.06.2022, 420
import pandas as pd
df = pd.read_csv('tmp.csv', parse_dates=['date'], dayfirst=True)
df['date'] = df['date'].dt.strftime('%m/%d/%Y')
print(df)

output:

         date   value
0  05/30/2022     4.2
1  05/31/2022    42.0
2  06/01/2022   420.0

  • Related