Home > Back-end >  Python how to replace values in a column in csv
Python how to replace values in a column in csv

Time:11-07

I would like to change and replace some values under some conditions.

My csv looks like:

   Date
0  2022-11-05
1  2022-11-06
2  2022-11-08
3  2022-11-09

I want the date 2 if it is Saturday and 1 if it is Sunday, and replace the value in the original csv.

df = pd.read_csv('Book1.csv')
date = df["Date"]
for d in date:
    date_object = datetime.strptime(d, '%Y-%m-%d').date()
    #print(date_object)
    weekdayidx=date_object.isoweekday()
    #print(weekdayidx)
    if weekdayidx == 6:
       date_final = date_object.replace(day=date_object.day   2)
    elif weekdayidx == 7:
       date_final = date_object.replace(day=date_object.day   1)
    else:
        date_final = date_object
    print(date_final)
df['Date'] = df['Date'].replace({'d': 'date_final'})
df.to_csv("Book1.csv", index=False)
print(df)

But still the result is the same as the original csv, no update, not sure about the reason.

Output:

0  2022-11-05
1  2022-11-06
2  2022-11-08
3  2022-11-09

But I want:

2022-11-07
2022-11-07
2022-11-08
2022-11-09

Thanks!

CodePudding user response:

I made some slight changes and this appears to work. With the changes I made, I'm just updating the data frame as a multidimensional array.

df = pd.read_csv('Book1.csv')
date = df["Date"]
for i in range(0, len(date)):
    d = date[i]
    date_object = datetime.strptime(d, '%Y-%m-%d').date()
    #print(date_object)
    weekdayidx=date_object.isoweekday()
    #print(weekdayidx)
    if weekdayidx == 6:
       date_final = date_object.replace(day=date_object.day   2)
    elif weekdayidx == 7:
       date_final = date_object.replace(day=date_object.day   1)
    else:
        date_final = date_object
    print(date_final)
    date[i] = date_final
df.to_csv("Book1.csv", index=False)
print(df)

CodePudding user response:

Loop through each row as follows:

import pandas as pd
from datetime import datetime

df = pd.read_csv('Book1.csv')

for i in range(len(df)):
    d = df.iloc[i].Date
    date_object = datetime.strptime(d, '%Y-%m-%d').date()
    #print(date_object)
    weekdayidx=date_object.isoweekday()
    #print(weekdayidx)
    if weekdayidx == 6:
       date_final = date_object.replace(day=date_object.day   2)
    elif weekdayidx == 7:
       date_final = date_object.replace(day=date_object.day   1)
    else:
        date_final = date_object
    print(date_final)
    df.iloc[i].Date = date_final
    
df.to_csv("Book1.csv", index=False)
print(df)
  • Related