Plotting CSV rows/columns simpler on Python

2.7k Views Asked by At

I have a csv file I am trying to read. The first row in the excel/csv sheet is the column headers "Jan|Feb|Mar..." etc. Then below each column header is float data. I have the following code:

filename ='Data.csv'
with open(filename) as f:
csvreader = csv.reader(f)
header_row = next(csvreader)
Jan, Feb = [], [] .... #(and so on)
Mar = []
Apr = []
May = []
Jun = []
Jul = []
Aug = []
Sep = []    
Oct = []
Nov = []
Dec = []
for row in csvreader:
    Jan.append(float(row[1]))
    Feb.append(float(row[2]))
    Mar.append(float(row[3]))
    Apr.append(float(row[4]))
    May.append(float(row[5]))
    Jun.append(float(row[6]))
    Jul.append(float(row[7]))
    Aug.append(float(row[8]))
    Sep.append(float(row[9]))
    Oct.append(float(row[10]))
    Nov.append(float(row[11]))
    Dec.append(float(row[12]))

How can I condense this code so I can easily plot a bar graph with the months on the x-axis and the data on the y-axis?

2

There are 2 best solutions below

6
On BEST ANSWER

For me, the easiest way is to use pandas library, as it provides plotting abilities straight from the dataframe.

import pandas as pd

df = pd.read_csv('Data.csv', sep='|') # or your sep in file
...
df.plot.bar()

Edit: If you have data in excel, there is no need to provide sep as it is for csv file. To read excel file it's as simple as:

df = pd.read_excel('Data.xlsx', sheetname='name')
df.plot.bar()

http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_excel.html

Some examples:

df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2.plot.bar()

Pandas documentation of barplot: https://pandas.pydata.org/pandas-docs/stable/visualization.html#visualization-barplot

0
On

Fake data / setup:

import csv, io
from pprint import pprint
from matplotlib import pyplot as plt

s = '''a, b, c
1, 2, 3
4, 5, 6
7, 8, 9'''
csv_file = io.StringIO(s)
reader = csv.reader(csv_file)

csv.reader objects return rows

header = next(reader)
data_rows = list(reader)

>>> pprint(data_rows, width = 20)
[['1', ' 2', ' 3'],
 ['4', ' 5', ' 6'],
 ['7', ' 8', ' 9']]
>>>

You can use zip() to transpose the data into columns

data_cols = zip(*data_rows)

>>> pprint(list(data_cols), width = 20)
[('1', '4', '7'),
 (' 2', ' 5', ' 8'),
 (' 3', ' 6', ' 9')]
>>> 

You can associate the columns with their header, again using zip, and add a legend to the plot

for month, data in zip(header, data_cols):
    plt.plot(data, label = month)
plt.legend()
plt.show()
plt.close()

enter image description here


If you just want to get the data into a container and have the columns associated with their headers, put it in a dict:

data = {}
for month, column in zip(header, data_cols):
    data[month] = column

>>> data
{'a': ('1', '4', '7'), ' b': (' 2', ' 5', ' 8'), ' c': (' 3', ' 6', ' 9')}
>>>