[英]Splitting a single column in a .csv file into multiple columns with changes in headings and saving it in a new .csv file using Python 2
I have a .csv file named selected.csv in C:\\Users\\Win-8.1\\Desktop\\delhi that contains 3 columns: 我在C:\\ Users \\ Win-8.1 \\ Desktop \\ delhi中有一个名为selected.csv的.csv文件,其中包含3列:
Entries | Date (LT) | AQI | Raw Conc.
First Entry 01-01-2016 00:00 316 322
Last Entry 31-12-2016 24:00 316 264
Now, what I want to do is: 现在,我想做的是:
i) Copy the data from this .csv file into a new empty .csv file named corrected.csv which I have created in the same folder. i)将数据从此.csv文件复制到新的空.csv文件中,该文件名为我在同一文件夹中创建的corrected.csv 。
The desired output should look like: 所需的输出应如下所示:
Entries | Date | Month | Hour | AQI | Raw Conc.
First Entry 1 January 12 AM 316 322
Last Entry 31 December 11 PM 316 264
import csv
from datetime import datetime
output_file = open('C:\Users\Win-8.1\Desktop\delhi\corrected.csv', 'w')
fieldnames = ['Entries', 'Date', 'Month' , 'Hour', 'AQI' , 'Raw Conc']
writer = csv.DictWriter(output_file, fieldnames=fieldnames)
writer.writeheader()
with open('C:\Users\Win-8.1\Desktop\delhi\selected.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
output_row = {}
output_row['Entries'] = row['Entries']
change_date = datetime.strptime(row['Date (LT)'], '%d-%m-%Y %H:%M')
output_row['Date'] = change_date.strftime('%d')
output_row['Month'] = change_date.strftime('%B')
output_row['Hour'] = change_date.strftime('%I %p')
output_row['AQI'] = row['AQI']
output_row['Raw Conc'] = row['Raw Conc']
writer.writerow(output_row)
output_file.close()
Note : I haven't tested the code so if you face any error let me know. 注意:我尚未测试代码,因此如果您遇到任何错误,请告诉我。
This is solution for your problem, but I would seriously suggest you to read more about Python CSV and Python Datetime library.This will help you for your future problem. 这是解决您问题的方法,但我会建议您阅读更多有关Python CSV和Python Datetime库的信息。这将对您将来的问题有所帮助。
The working code to the posted question is as follows: 发布的问题的工作代码如下:
import csv
from datetime import datetime
output_file = open(r"C:\Users\Win-8.1\Desktop\delhi\corrected.csv", "wb")
fieldnames = ['Date', 'Month' , 'Year', 'Hour', 'AQI' , 'Raw Conc.']
writer = csv.DictWriter(output_file, fieldnames=fieldnames)
writer.writeheader()
with open(r"C:\Users\Win-8.1\Desktop\delhi\selected.csv") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
output_row = {}
change_date = datetime.strptime(row['Date (LT)'], '%d-%m-%Y %H:%M')
output_row['Date'] = change_date.strftime('%d')
output_row['Month'] = change_date.strftime('%B')
output_row['Year'] = change_date.strftime('%Y')
output_row['Hour'] = change_date.strftime('%I %p')
output_row['AQI'] = row['AQI']
output_row['Raw Conc.'] = row['Raw Conc.']
writer.writerow(output_row)
output_file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.