0

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

Oguz Han
  • 29
  • 8
  • It's going to be hard to import a CSV that uses comma as a decimal separator - I'd address that separately - see [Convert commas decimal separators to dots within a Dataframe](https://stackoverflow.com/questions/31700691/convert-commas-decimal-separators-to-dots-within-a-dataframe). The date issue is relatively straightforward. – Steve Jun 01 '22 at 08:30
  • Also perhaps you could elaborate on "doesn't work" - see [Ask] – Steve Jun 01 '22 at 08:32
  • I changed the separators. The problem is changing the date format :) ps: df.Tarih=df.Tarih.str.replace(".","/") is wrong – Oguz Han Jun 01 '22 at 08:40

1 Answers1

2

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

Steve
  • 1,579
  • 10
  • 23
  • There are other ways of changing the representation of the date - see the range of answers on [How to change the datetime format in Pandas](https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas) – Steve Jun 01 '22 at 09:01
  • Thank you for the examples. My problem is solved – Oguz Han Jun 01 '22 at 20:57