首页 > 解决方案 > 有没有比 csv.DictReader 更好的方法来编译来自多个文件的列数据?

问题描述

前言:我对这项工作非常陌生(就像上周刚开始的那样),所以如果我的绿色表现出来,我提前道歉。

我有 3 个独立的大型数据文件,代表不同时间点的特定距离。每个文件占总时间的三分之一,分为 53 列,第一列是时间戳,另外 52 列分别是测量的不同距离,分别命名为 01A、01B、02A、02B 等。我的终极目标是创建一个直方图,将所有三个文件中每个距离的数据(例如 01A)组合起来。

我想出了这个非常适合我制作的较小样本数据文件的方法:

import csv 
import matplotlib.pyplot as plt 
Countries = []
with open("python_practice.txt", "r") as csv_file: 
    csv_file.readline()[1:]
    csv_reader = csv.DictReader(csv_file, delimiter='\t') 
    for lines in csv_reader:
        Country = lines['country'] 
        Countries.append(Country)
with open("python_practice1.txt", "r") as csv_file1: 
    csv_reader1 = csv.DictReader(csv_file1, delimiter='\t')
    for lines in csv_reader1: 
        Country1 = lines['country']
        Countries.append(Country1)

data = Countries
plt.hist(data, bins='auto')

但是,当我试图通过以下方式使其适用于我的实际数据的单个文件时:

import csv 
import matplotlib.pyplot as plt 

Distances = []
with open("distances_1.traj", "r") as csv_file: 
    csv_file.readline()[1:]
    csv_reader = csv.DictReader(csv_file, delimiter='\t') 
    for lines in csv_reader:
        Distance = lines['01A'] 
        Distances.append(Distance)

data = Distances
plt.hist(data, bins='auto')

我得到一个 KeyError:'01A'

我不确定为什么 DictReader 无法“识别”列名 01A,或者如何解决此问题。因此,这里欢迎任何和所有建议。

标签: pythoncsvmatplotlibhistogram

解决方案


推荐阅读