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

3
  • 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. The date issue is relatively straightforward. Commented Jun 1, 2022 at 8:30
  • Also perhaps you could elaborate on "doesn't work" - see How to Ask Commented Jun 1, 2022 at 8:32
  • I changed the separators. The problem is changing the date format :) ps: df.Tarih=df.Tarih.str.replace(".","/") is wrong Commented Jun 1, 2022 at 8:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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
Thank you for the examples. My problem is solved

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.