我的csv文件有两列,第一列是日期,第二列是该日期的平均温度。我试图使我的代码仅从第二列(第1-366行)中打印第一年的数据,但是我很难找到一种方法来执行此操作。我希望代码能够打印前几年的行以及标题为“是第一年是2010年”的标题。
这是我使用的控制器:
import FunctionLibrary
ConfigData = FunctionLibrary.CSV_Read('CSV.csv')
#print(ConfigData)
Data = FunctionLibrary.CSV_Read('CSV.csv')
a=FunctionLibrary.MeanCalc([1:365])
print(a)
这是函数库:
import csv
from matplotlib import pyplot
import numpy as np
from os.path import isfile
import math
import statistics
from collections import defaultdict
from csv import reader
data=defaultdict(list)
with open ('CSV.csv') as f:
rd = csv.DictReader(f)
for i in rd:
for j in i.keys():
data[j].append(i[j])
#print({k:v for k,v in data.items()})
def col_extract(FileName):
reader= csv.reader(FileName, delimiter=' ')
included_cols=[1,2]
for row in reader:
content = list(row[1:366] for i in inculded_cols)
return content
#print(col_extract('CSV.csv'))
def CSV_Read(FileName):
with open(FileName) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count==0:
Header=row
lstf=[[] for i in range(len(Header))]
else:
index=0
for item in row:
lstf[index].append(item)
index+=1
line_count += 1
return [line_count-1, Header, lstf]
def Trend(Data, ColNum1, ColNum2):
z=np.polyfit([float(item) for item in Data[ColNum1]],[float(item) for
item in Data[ColNum2]],1)
return z
def CSV_Write(FileName, Data, Header):
new = not isfile(FileName) #checks if the file exists
#Potential improvement: if the file exists use your CSV_Read function to
ensure the number of columns in Data match number of columns in file
with open(FileName, 'a',newline='') as csvfile:
writer = csv.writer(csvfile)
if new: writer.writerow(Header)
resortedData = [[Data[i][r] for i in range(len(Data))]for r in
range(len(Data[0]))] #convert the elements of the list from columns to rows
for r in resortedData:
writer.writerow(r)
def MeanCalc(FileName, x):
#from filename import meantemp as d
a=statistics.mean(FileName/365)
return a
print(MeanCalc('CSV.csv',[2][1:366]))
如您所见,我尝试了多种功能,但似乎没有一种对我有用。