CSV in, charts out

Part of the free LogicWiz Python course, Module 10: NumPy and pandas. The examples and practice run in the app.

Canteen Counter v1 already saves each day's sales to sales.csv. Shankar bhaiya wants a bar chart of revenue per item for the notice board, and a clean report file for the college accounts office.

You'll learn to

  • Load a CSV with `read_csv` and save one with `to_csv(index=False)`
  • Draw line, bar and histogram charts with Matplotlib
  • Label charts properly: title, axis labels, legend

Learn

read_csv: a file becomes a DataFrame

import pandas as pd

df = pd.read_csv("sales.csv")
print(df.head(3))
print(df.shape)
print(df.dtypes)

The first line of the file becomes the column names, and pandas guesses each column's type. Use header=None, names=[...] if the file has no header line, and index_col="roll" to use a column as the row labels.

to_csv: save a report

import pandas as pd

df = pd.read_csv("sales.csv")
df["amount"] = df["qty"] * df["price"]
per_day = df.groupby("day", sort=False)["amount"].sum().reset_index()
per_day.to_csv("daily.csv", index=False)
print(open("daily.csv").read())

reset_index() turns the group labels (day) back into an ordinary column, so the file gets a day,amount header.

to_csv writes the index too, unless you say index=False. Read such a file back and you get a mystery column called Unnamed: 0. And if a CSV has no header line, read_csv turns your first data row into column names; pass header=None.

Which chart?

ChartUse it for
Line: plt.plot(x, y)A trend over time: plates sold Mon to Sun
Bar: plt.bar(labels, values)Comparing categories: revenue per item
Histogram: plt.hist(values, bins=...)How values are spread: how many students scored 60-70

A line chart with a legend

import matplotlib.pyplot as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
chai = [120, 95, 140, 110, 180, 240]
samosa = [80, 70, 90, 85, 120, 150]
plt.plot(days, chai, marker="o", label="Chai")
plt.plot(days, samosa, marker="s", label="Samosa")
plt.title("Plates sold this week")
plt.xlabel("Day")
plt.ylabel("Plates")
plt.legend()
plt.show()

label= names each line, and plt.legend() shows those names. Every chart needs a title and labelled axes; examiners deduct marks without them.

From CSV to a bar chart

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("sales.csv")
df["amount"] = df["qty"] * df["price"]
totals = df.groupby("item")["amount"].sum().sort_values(ascending=False)
print(totals)
plt.bar(totals.index, totals.values, color="orange")
plt.title("Revenue by item")
plt.xlabel("Item")
plt.ylabel("Rs")
plt.show()

pandas can also draw directly: totals.plot(kind="bar"). Under the hood it calls Matplotlib.

A histogram of marks

import matplotlib.pyplot as plt

marks = [35, 42, 48, 55, 58, 61, 63, 67, 70, 72, 75, 78, 81, 85, 88, 92, 95]
plt.hist(marks, bins=[30, 40, 50, 60, 70, 80, 90, 100], edgecolor="black")
plt.title("Class 12 IP marks")
plt.xlabel("Marks")
plt.ylabel("Number of students")
plt.show()

Each bar counts how many values fall in a bin: 30-40, 40-50, and so on. A bar chart compares named things; a histogram shows how one set of numbers is spread.

CBSE IP Class 12 (Data Visualisation) covers line, bar and histogram charts with title, xlabel, ylabel, legend and savefig, plus "Import and export data between pandas and CSV files". Practical-file programs: plot a line chart of a week's temperatures, a bar chart of subject-wise marks, and a histogram of class marks. Save with plt.savefig("chart.png") before plt.show().

In one line

pd.read_csv(path) loads a table (header=None if there is no header line); df.to_csv(path, index=False) saves one; plt.plot for trends, plt.bar for categories, plt.hist for spread, always with a title and axis labels.

Interview corner

How do you read and write CSV files with pandas? Name some useful options.

pd.read_csv(path) and df.to_csv(path, index=False). Useful read_csv options: header=None and names=[...] for files without a header, index_col to use a column as the index, usecols to load only some columns, parse_dates for dates, sep for other delimiters, and nrows/chunksize for big files.

When would you use a bar chart vs a histogram?

A bar chart compares values across named categories (revenue per item). A histogram shows the distribution of one numeric variable by counting values in bins (how many students scored 60-70). In a histogram the bars touch because the bins are continuous.

What is the difference between `plt.show()` and `plt.savefig()`?

savefig("chart.png") writes the current figure to a file; show() displays it and, in scripts, usually closes it. Call savefig before show, or you may save an empty figure.