0

I'm new in python. I want to read data from a csv file, and then create a graph from those data. I have a csv file with 2 columns and 20 row. In the first row I have 1 1, second row have 2 2, and so on, until 20 20. I want to take this coordinates and make graph.

This is what I have so far:

import csv
from pylab import *

with open('test.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') # open the csv file
    for row in spamreader:
        print ', '.join(row) #  in each loop, row is getting the data,
                             # first row is [1,1] , then [2,2] and so on

plot()
show()

Now, What I was thinking is to make row to be in the end, with 2 cols and 20 row with all data. Then I need to do parameter x, to be the first col, and y to be the second col, and give plot the x,y.

My problem is that I don't know how to save all values in row, and how to take only the first col and second col.

Thank you all!

2 Answers 2

1

You had problems in reading csv file
1) delimiter = ','

Regarding populating the x and y values for the graph. Just read the first and second values of each row and populate the x and y lists.

Here is the modified code:

import csv
from pylab import *

with open('test.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') # open the csv file
    x = []
    y = []
    for row in spamreader:
        x.append(row[0])
        y.append(row[1])
        print ', '.join(row) #  in each loop, row is getting the data,
                         # first row is [1,1] , then [2,2] and so on

plot(x, y)
show()
Sign up to request clarification or add additional context in comments.

1 Comment

Actually Vikash's answer is more elegant as "zip" is ideal for such kind of computation. The change of splitting the row with "," would work just fine. But since you are new to python I guess my answer would be easier to understand.
0

You can use this to get your X and Y axis:

with open('./test4.csv', 'rb') as csvfile:
    (X,Y) = zip(*[row.split() for row in csvfile])

2 Comments

Hi, I was doing this: import csv from pylab import * with open('test.csv', 'rb') as csvfile: (X,Y) = zip(*[row.split() for row in csvfile]) #spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') #for row in spamreader: # print ', '.join(row) plot() show() But I'm getting an error: (X,Y) = zip(*[row.split() for row in csvfile]) ValueError: need more than 1 value to unpack
that must be because of format of data. Just print this, [row.split() for row in csvfile] and let me know what do you get? If your values are separated by commas then instead split(',') will work.

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.