【问题标题】:How to store the row value from csv in python?如何在python中存储来自csv的行值?
【发布时间】:2018-07-13 18:07:14
【问题描述】:

我有一个用 C++ 构建的主程序,它生成一个 CSV 文件。我已经使用 PyQt5 创建了一个接口,我想从该 CSV 中读取一些特定的列。

我可以阅读,但我想存储它们以使用 matplotlib 制作绘图。可能我的错是我试图使用该行,就像它是一个数组一样。这是我的 readfile 函数的外观:

def readCSV(self):
    try:
        with open('resultado.csv') as csvFile:
            reader = csv.DictReader(csvFile, delimiter=';')
            i = 0
            x, y = []
            for row in reader:
                print(row["TOA (ns)"], row["Frecuencia Inicial (MHz)"])
                x[i] = row["TOA (ns)"]
                y[i] = row["Frecuencia Inicial (MHz)"]
                i = i+1
    except:
        print("Error: ", sys.exc_info()[0])

异常打印: 错误:类“ValueError”

这是我的 csv 的前 2 行,下一行都是浮点值。我只想要 TOA 和 Frecuencia Inicial 列:

【问题讨论】:

  • 请。显示 CSV 文件的第一行
  • 显示的列得到了标题Frecuencia Inicial,没有(MHz)。这也可能是错误的来源。但是异常会在其他地方抛出,因为错误的列名会抛出 KeyError。你能说出实际引发错误的那一行吗?
  • x, y = [] 将尝试将一个空列表解压缩为两个变量。这引发了ValueError: not enough values to unpack (expected 2, got 0)

标签: python csv


【解决方案1】:

对您的代码进行一些更改:只需将值附加到 x 和 y 数组,使用精确的列名

 def readCSV():
     with open('resultado.csv') as csvFile:
        reader = csv.DictReader(csvFile, delimiter=';')
        x, y = [], [] 
        for row in reader:
            try:
                print(row["TOA (ns)"], row["Frecuencia Inicial"])
                # guess you want
                x.append(row["TOA (ns)"])
                y.append(row["Frecuencia Inicial"])
                #i = i+1
            except Exception as e:
                print("Error: ", e)

     # do something with x, y
     # since you use 'self' in the function def I asume this is
     # a class method, so you could make x and y class properties
     # and then use self.x and self.y in this code

     print(x)
     print(y)

您可能想查看 Pandas 的使用情况:

import pandas as pd
df = pd.read_csv("/tmp/indata.csv", delimiter=";")
df
   TOA (ns)  Frecuencia Inicial  
0        10                2000   
1        20                3000

从 jupyter 笔记本中,您可以使用以下方法进行绘图:

df[['TOA (ns)', 'Frecuencia Inicial']].plot(figsize=(20,10))

您仍然可以使用 matplotlib 微调您的绘图并使用来自 Pandas 数据框的数据

【讨论】:

  • 那行不通,请参阅我关于x, y = []的问题下方的评论
  • @shmee : 我已经修改了
猜你喜欢
  • 2022-06-28
  • 2021-10-14
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 2017-09-02
相关资源
最近更新 更多