2

as the title explains I'm trying to read in a CSV file and plot it, the file is in the following format:

Dishwasher,60,1,1,1,0,0,1

Washing Machine,200,0,0,0,0,1,1

where I just want to plot the 6 digits at the end.

Here is my code so far:

import matplotlib.pyplot as plt
import numpy as np
import csv
y1=[]
y2=[]

x = np.array([1,2,3,4,5,6])
with open('File.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
y1=int((rows[0])-2)
y2=int((rows[1])-2)

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.show()

I've been trying to solve the problem for hours now but everything I do brings about a new error.

In this code, the error is:

TypeError: unsupported operand type(s) for -: 'list' and 'int'

Which from my understanding means it's trying to convert a list into an integer which isn't possible? Thanks for any and all help

3 Answers 3

4

in those 2 lines:

y1=int((rows[0])-2)
y2=int((rows[1])-2)

you are taking the first and second elements of the list subtracting 2 and transforming on an int the assigning it to the variables y1 and y2 that means you cant subtract an int from a list

i recommend you to inspect your values before plotting it you can use the debugger or just print rows, y1 and y2 and you will have more insight on what is going on

the error tells you exactly what is going on:

TypeError: unsupported operand type(s) for -: 'list' and 'int'  

obs try this out:

y1=rows[0][2:]
y2=rows[1][2:]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, its working now but i still face the problem of excluding those first two elements in each row, how could i skip over them?
1

First your rows is a list containing tuples, thus with rows[0] you refer to the first tuple not the integer inside. You have to go deeper to pick it.

Second you substract a string with an integer with this expression : int((rows[0])-2) (because you convert after substracting and not before)

Third, you must pass an iterable to the plot function which is x-length

so I just see you provide the csv, the script works with my csv rebuild file

import matplotlib.pyplot as plt
import numpy as np
import csv
y1=[]
y2=[]

x = np.array([1,2,3,4,5,6])
with open('File.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=';')
    rows = [row for row in plots]

y1=[int(row[0])-2 for row in rows]
y2=[int(row[1])-2 for row in rows]

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.show()

Comments

0

It looks like rows is array of arrays. Rows[0] is array and you trying to do rows[0] - 2

Comments

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.