Python如何在csv中替换列中的值

wfypjpf4  于 2022-12-06  发布在  Python
关注(0)|答案(2)|浏览(134)

我想在某些条件下更改和替换一些值。
我的csv看起来像:

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

我想要的日期+2如果它是星期六和+1如果它是星期日,并取代在原来的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)

但结果还是和原来的csv一样,没有更新,不确定原因。
输出量:

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

但我希望:

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

谢谢你!

hts6caw3

hts6caw31#

我做了一些小的修改,这似乎是工作。与我所做的更改,我只是更新数据框作为一个多维数组。

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)
ax6ht2ek

ax6ht2ek2#

按如下方式循环遍历每行:

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)

相关问题