我想从CSV文档中用python创建图形,但是只能显示一对数字,我该如何完成?

时间:2018-09-07 13:18:40

标签: python python-3.x

import os
from matplotlib import pyplot as pyplot
from collections import defaultdict
import numpy as np
import csv
path = r'C:/Users/AK6PRAKT'
dirs = os.listdir(path) 
s = []
for i in dirs:                             
    if os.path.splitext(i)[1] == ".csv": 
        f = open(path+"/"+i)
        iter_f = iter(f);
        str = ""
        for line in iter_f: 
              str = str + line
        s.append(str) 
        with open(path+"/"+i,'r') as r:
            lines=r.readlines()
        with open(path+"/"+i,'w') as w:
            for row in lines:
                if 'Date' not in row:
                    w.write(row)
        from collections import defaultdict
        columns = defaultdict(list)
        import csv
        with open(path+"/"+i) as f:
            reader = csv.reader(f)
            for row in reader:
                for (i,v) in enumerate(row):
                    columns[i].append(v)
        print(columns[0],columns[1])
fig = pyplot.figure()
ax1 = fig.add_subplot(1,1,1)
pyplot.plot(columns[0],columns[1])
pyplot.show()

实际上,我的计算机中有超过40000个csv文件,首先,我在特定位置选择2个数字系列,一个是关于时间,另一个是关于电池状态,然后我要关于2个系列的图形,一个作为x轴,一个作为y轴。但是结果只显示了该系列的最后一对,但是我想在python中看到完整的图形。

1 个答案:

答案 0 :(得分:0)

您似乎正在做很多不必要的工作……据我所知,重要的只是:

from glob import glob
import csv

c1 = []
c2 = []

for path in glob('C:/Users/AK6PRAKT/**/*.csv', recursive=True):
  with open(path) as fd:
    rows = csv.reader(fd)
    # ignore header (I presume this is what your "'Date' not in row" is about)
    next(rows)
    for cols in rows:
      c1.append(cols[0])
      c2.append(cols[1])