pandas: Filter rows with combined masks

Model df[(cond1) & (cond2) | (cond3)]: masks combined value by value, with & binding before |.

What to build

A program that filters a table with conditions joined by & and |.

Requirements

  • A condition is COLUMN OP VALUE with OP one of >, <, >=, <=, ==, !=. When VALUE is a number, compare numerically, otherwise compare text.
  • & binds more tightly than |, as in Python and pandas. Print the names of the matching rows separated by spaces, or no rows.

Input

Line 1: the header (the first column is name). Line 2: n. Then n rows, values separated by commas. Next line: q. Then q filters.

Output

q lines.

Constraints

1 ≤ n ≤ 100; 1 ≤ q ≤ 20; numeric columns hold numbers only.

Example

Input:

name,age,city
4
Ada,36,London
Rahim,24,Dhaka
Mei,29,Tokyo
Omar,41,Dhaka
3
age > 25 & city == Dhaka
city == Tokyo | age < 25
age >= 50

Output:

Omar
Rahim Mei
no rows

Why it works

Each condition gives a mask of one boolean per row; & and | combine two masks position by position, so the final mask keeps exactly the rows that satisfy the whole expression.

Examples

Example 1 · Input
name,age,city
4
Ada,36,London
Rahim,24,Dhaka
Mei,29,Tokyo
Omar,41,Dhaka
3
age > 25 & city == Dhaka
city == Tokyo | age < 25
age >= 50
Expected output
Omar
Rahim Mei
no rows
Example 2 · Input
name,score
3
a,10
b,20
c,30
1
score != 20
Expected output
a c

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

Hints

Hint 1

Split the filter on " | " into groups and each group on " & "; a row passes if every condition of any group holds.

Hint 2

Compare as numbers when the value is a number, otherwise as text.

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 number(text):
    try:
        return float(text)
    except ValueError:
        return None


def holds(row, condition):
    column, op, value = condition.split(" ", 2)
    if number(value) is not None:
        return OPS[op](float(row[column]), float(value))
    return OPS[op](row[column], value)


header = input().split(",")
n = int(input())
rows = [dict(zip(header, input().split(","))) for _ in range(n)]
q = int(input())
for _ in range(q):
    groups = [g.split(" & ") for g in input().split(" | ")]
    names = [r["name"] for r in rows if any(all(holds(r, c) for c in g) for g in groups)]
    print(" ".join(names) if names else "no rows")

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