pandas: Change values through loc

Model df.loc[mask, "column"] = value, the safe way to change some rows of a table, including creating a new column.

What to build

A program that applies conditional updates to a table and prints the result.

Requirements

  • Each update is COLUMN OP VALUE => TARGET = NEWVALUE: in the rows where the condition holds, TARGET becomes NEWVALUE. Conditions compare numerically when VALUE is a number.
  • Updates are applied in order, each seeing the results of the earlier ones. If TARGET is a new column, it is added at the end and the rows not selected get NaN.
  • Finally print the header joined by commas, then each row joined by commas.

Input

Line 1: the header. Line 2: n. Then n rows. Next line: u. Then u updates.

Output

n + 1 lines.

Constraints

1 ≤ n ≤ 50; 1 ≤ u ≤ 20; values contain no commas or spaces.

Example

Input:

name,age,city
3
Ada,36,London
Rahim,24,Dhaka
Omar,41,Dhaka
2
city == Dhaka => age = 0
age > 30 => group = senior

Output:

name,age,city,group
Ada,36,London,senior
Rahim,0,Dhaka,NaN
Omar,0,Dhaka,NaN

Why it works

The mask picks rows and the column name picks one column, so loc changes exactly those cells in the original table; a brand-new column needs a value in every row, and NaN fills the rows the mask left out.

Examples

Example 1 · Input
name,age,city
3
Ada,36,London
Rahim,24,Dhaka
Omar,41,Dhaka
2
city == Dhaka => age = 0
age > 30 => group = senior
Expected output
name,age,city,group
Ada,36,London,senior
Rahim,0,Dhaka,NaN
Omar,0,Dhaka,NaN
Example 2 · Input
item,price
2
pen,20
lamp,900
1
price < 100 => price = 25
Expected output
item,price
pen,25
lamp,900

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

Hints

Hint 1

For each update, build the mask from the condition, then set the column in the rows where it is True.

Hint 2

A column that does not exist yet is created, with NaN in the rows the mask does not select.

Solution

Show one correct solution (try it yourself first)
import operator

OPS = {">": operator.gt, "<": operator.lt, ">=": operator.ge, "<=": operator.le, "==": operator.eq, "!=": operator.ne}


def holds(cell, op, value):
    try:
        return OPS[op](float(cell), float(value))
    except ValueError:
        return OPS[op](cell, value)


header = input().split(",")
n = int(input())
rows = [dict(zip(header, input().split(","))) for _ in range(n)]
u = int(input())
for _ in range(u):
    condition, assignment = input().split(" => ")
    column, op, value = condition.split(" ")
    target, new = [p.strip() for p in assignment.split("=")]
    if target not in header:
        header.append(target)
        for row in rows:
            row[target] = "NaN"
    for row in rows:
        if holds(row[column], op, value):
            row[target] = new
print(",".join(header))
for row in rows:
    print(",".join(row[h] for h in header))

Lesson: Selecting rows and columns: loc, iloc and masks →