Hello Experts我有一个程序可以读取包含多列的csv文件。这个程序的主要目的是将字符串转换为数字的序列,重复的字符串将是我能执行的所有操作的相同数字,但我希望我的日期/时间列只打印日期,为此我应用了一种切片方法控制台,但我无法将其打印到我的另一个csv文件上。请告诉我该怎么办。
这是我写的程序:
import pandas as pd
import csv
import os
# from io import StringIO
# tempFile="input1.csv"
with open("input1.csv", 'r',encoding="utf8") as csvfile:
# creating a csv reader object
reader = csv.DictReader(csvfile, delimiter=',')
# next(reader, None)
'''We then restructure the data to be a set of keys with list of values {key_1: [], key_2: []}:'''
data = {}
for row in reader:
# print(row)
for header, value in row.items():
try:
data[header].append(value)
except KeyError:
data[header] = [value]
'''Next we want to give each value in each list a unique identifier.'''
# Loop through all keys
for key in data.keys():
values = data[key]
things = list(sorted(set(values), key=values.index))
for i, x in enumerate(data[key]):
if key=="Date/Time":
var = data[key]
iter_obj1 = iter(var)
while True:
try:
element1 = next(iter_obj1)
date =element1[0:10]
print("date-",date)
except StopIteration:
break
break
else:
# if key == "Date/Time" :
# print(x[0:10])
# continue
data[key][i] = things.index(x) + 1
print('data.[keys]()-',data[key])
print('data.keys()-',data.keys())
print('values-',values)
print('data.keys()-',key)
print('x-',x)
print('i-',i)
# print("FullName-",FullName)
"""Since csv.writerows() takes a list but treats it as a row, we need to restructure our
data so that each row is one value from each list. This can be accomplished using zip():"""
with open("ram3.csv", "w") as outfile:
writer = csv.writer(outfile)
# Write headers
writer.writerow(data.keys())
# Make one row equal to one value from each list
rows = zip(*data.values())
# Write rows
writer.writerows(rows)
注意:我不能使用熊猫DataFrame
。这就是为什么我写了这样的代码。请告诉我如何打印我的日期/时间列,只打印我需要更改代码才能获得的日期。。。感谢
输入:
job_Id Name Address Email Date/Time
1 snehil singh marathalli ss@gmail.com 12/10/2011:02:03:20
2 salman marathalli ss@gmail.com 12/11/2011:03:10:20
3 Amir HSR ar@gmail.com 11/02/2009:09:03:20
4 Rakhesh HSR rakesh@gmail.com 09/12/2010:02:03:55
5 Ram marathalli r@gmail.com 01/10/2014:12:03:20
6 Shyam BTM ss@gmail.com 12/11/2012:01:03:20
7 salman HSR ss@gmail.com 11/08/2016:15:03:20
8 Amir BTM ar@gmail.com 07/10/2013:04:02:30
9 snehil singh Majestic sne@gmail.com 03/03/2018:02:03:20
Csv文件:
job_Id Name Address Email Date/Time
1 1 1 1 12/10/2011:02:03:20
2 2 1 1 12/11/2011:03:10:20
3 3 2 2 11/02/2009:09:03:20
4 4 2 3 09/12/2010:02:03:55
5 5 1 4 01/10/2014:12:03:20
6 6 3 1 12/11/2012:01:03:20
7 2 2 1 11/08/2016:15:03:20
8 3 3 2 07/10/2013:04:02:30
9 1 4 5 03/03/2018:02:03:20
在这个输出中,所有内容都是正确的,但只有日期/时间列。我只想打印日期,不想打印时间。
if key=="Date/Time":
var="12/10/2011"
print(var)
var = data[key]
iter_obj1 = iter(var)
while True:
try:
element1 = next(iter_obj1)
date =element1[0:10]
print("date-",date)
except StopIteration:
break
我明白了,我不应该用这些。。。只添加了一行内容就会在for循环中打印出所需的输出。。
if key=="Date/Time":
data[key][i] = data[key][i][0:10]
就这样……一切都会一样的。。