Search code examples
pythoncsvmatplotlibgraph

Make Matplotlib Ignore Headings


My friend is trying to make a graph using the python import matplotlib and a CSV file I have given her. However, the CSV I've given her includes headings (COUNTRY, COST) so the py program is unable to run properly. The error says "could not convert string to float". Here is her code an example of my file. How can she make the bar chart ignore the first row of the CSV file so the code is able to run

Sample of the file, including the headings causing problems

import matplotlib.pyplot as plt
import csv

price = []
countries = []
    
with open ("CpremiumusersEurope.csv","r") as csvfile:
    plot = csv.reader(csvfile)
    for row in plot:
        price.append(float(row[1]))
        countries.append(str(row[0]))

plt.style.use('grayscale') 
plt.bar( countries, price, label='Europe', color='red')

plt.ylabel('Price in Europe ($)')
plt.title('Cost of spotify premium per country')
plt.xticks(rotation=90)

plt.legend(loc='best')
plt.show()

Solution

  • You can skip the first row like this:

    for idx, row in enumerate(plot):
        if idx == 0:
            continue 
        price.append(float(row[1]))
        countries.append(str(row[0]))
    

    You could also skip it in this way, which I like less as it's less flexible.

    for row in plot:
        if row[1] == 'COST':
            continue 
        price.append(float(row[1]))
        countries.append(str(row[0]))