Python:如何将从操作获得的值添加到给定CSV的新列中? [英] Python: How to add values obtained from an operation in a new column of given CSV?
本文介绍了Python:如何将从操作获得的值添加到给定CSV的新列中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个样例CSV,如下所示:
i have a sample CSV given as follows:
Name,Birthdate,Age,Address,Zone
ABC,3-10-2016 11:00:00AM,21,XYZ Street 21, zone
BCD,3-11-2016 15:54:00PM,22,WXY Street 21/A, S zone
CDW,4-11-2015 21:09:00PM,22,ZYX Street 21Avenue, North Zone
我使用以下代码从数据中的给定日期获取工作日:
i have used the following code to obtain the weekday from a given date in the data:
import csv
from datetime import datetime
with open(filename, 'rb') as infile:
reader = csv.DictReader(infile)
for row in reader:
birthdate = row['Birthdate'] # keys are named in the first row of your CSV
birthdate = datetime.strptime(birthdate, '%m-%d-%Y %H:%M:%S%p')
print birthdate.strftime('%A')
输出为:
Thursday
Friday
Saturday
我想将此输出附加到具有 weekday
的新列名称的同一个CSV中。
i want to append this output into the same CSV with a new column name as weekday
.
注意:上述代码和数据都是抽样的,原始数据是不同的。
NOTE: the above code and data are all sampled and original data is way different.
推荐答案
p>只是为了有趣
import re
from datetime import datetime as dt
def changedate(birthdate):
weekday = dt.strptime(birthdate, '%m-%d-%Y %H:%M:%S%p').strftime('%A')
return birthdate + ',' + weekday
str = open(filename).read()
str = re.sub(r'Name,Birthdate,Age,Address','Name,Birthdate,Weekday,Age,Address', str)
str = re.sub(r'(\d+-\d+-\d+\s\d+:\d+:\d+\w{2})',lambda m: changedate(m.group()), str)
with open(filename, 'w') as f:
f.write(str)
这篇关于Python:如何将从操作获得的值添加到给定CSV的新列中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文