我想在某些情况下更改和替换一些值。
我的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
谢谢!
我做了一些轻微的改变,这似乎工作。随着我所做的更改,我只是将数据帧更新为多维数组。
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)
按如下方式遍历每一行:
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)