1

I have a main program built in C++ that generates a CSV file. I've made an interface with PyQt5 and I want to read some specific columns from that CSV.

I can read but I want to store them to make a plot with matplotlib. Probably my fault is that I'm trying to work with the row like if it is an array. This is how my readfile function looks:

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])

The exception prints: Error: class 'ValueError'

This are the 2 first lines of my csv, the next line are all float values. I only want TOA and Frecuencia Inicial columns:

enter image description here

3
  • pls. show the first lines of the CSV file Commented Jul 13, 2018 at 9:23
  • The shown column got the Header Frecuencia Inicial without (MHz). This might also be a source for errors. But the exception is thrown somewhere else, as a wrong column name would throw a KeyError. Can you tell the line that's actually throwing the error? Commented Jul 13, 2018 at 9:32
  • 1
    x, y = [] will try to unpack an empty list into two variables. That raises ValueError: not enough values to unpack (expected 2, got 0) Commented Jul 13, 2018 at 9:41

1 Answer 1

3

Some changes to your code: just append the values to the x and y array, use columnnames exact

 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)

You might want to checkout the use of Pandas:

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

From a jupyter notebook you can do the plot with:

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

You can still finetune your plots using matplotlib and use data from a Pandas dataframe

Sign up to request clarification or add additional context in comments.

2 Comments

That won't work, see my comment below the question regarding x, y = []
@shmee : I've modified it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.