pandas: Add a computed column

Model df["total"] = df["price"] * df["qty"], the most common new column.

What to build

A program that adds a total column and a grand total.

Requirements

  • Add a column total equal to price × qty for each row, print the table with the new column (header first, values joined by commas), then grand total: G.

Input

Line 1: the header (it contains price and qty). Line 2: n. Then n rows.

Output

n + 2 lines.

Constraints

0 ≤ n ≤ 100; price and qty are whole numbers.

Example

Input:

item,price,qty
3
pen,20,3
book,350,1
lamp,900,2

Output:

item,price,qty,total
pen,20,3,60
book,350,1,350
lamp,900,2,1800
grand total: 2210

Why it works

Multiplying two columns pairs their values by row, so the new column lines up with the rest of the table, and summing it gives the grand total.

Examples

Example 1 · Input
item,price,qty
3
pen,20,3
book,350,1
lamp,900,2
Expected output
item,price,qty,total
pen,20,3,60
book,350,1,350
lamp,900,2,1800
grand total: 2210
Example 2 · Input
qty,price
1
0,5
Expected output
qty,price,total
0,5,0
grand total: 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

The new column is price × qty, row by row.

Hint 2

Add the new name to the header so it prints as a column.

Solution

Show one correct solution (try it yourself first)
header = input().split(",")
n = int(input())
rows = [input().split(",") for _ in range(n)]
p, q = header.index("price"), header.index("qty")
grand = 0
print(",".join(header + ["total"]))
for row in rows:
    total = int(row[p]) * int(row[q])
    grand += total
    print(",".join(row + [str(total)]))
print(f"grand total: {grand}")

Lesson: Transforming columns →