pandas: Stack two tables with concat

pd.concat([a, b], ignore_index=True) stacks two tables and aligns their columns by name. Model it.

What to build

A program that stacks two CSV tables.

Requirements

  • The result's columns are A's columns in order, followed by B's columns that are not in A, in B's order.
  • Print the header, then A's rows, then B's rows, each with values in the result's column order. A column a table does not have, or an empty cell, is printed as NaN.

Input

Table A: its header, then n, then n rows. Then table B in the same form.

Output

1 + n + m lines.

Constraints

0 ≤ n, m ≤ 50; no cell contains a comma; column names are unique within a table.

Example

Input:

name,age
2
Ana,31
Ben,25
name,age
1
Cy,40

Output:

name,age
Ana,31
Ben,25
Cy,40

Why it works

concat lines rows up by column name rather than by position, so values land under the right header even when the tables list their columns differently, and gaps become NaN.

Examples

Example 1 · Input
name,age
2
Ana,31
Ben,25
name,age
1
Cy,40
Expected output
name,age
Ana,31
Ben,25
Cy,40
Example 2 · Input
id,x
1
1,a
id,y
1
2,b
Expected output
id,x,y
1,a,NaN
2,NaN,b

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

Hints

Hint 1

Build the combined column list: A's columns, then B's columns that A lacks.

Hint 2

Turn each row into a dictionary from column name to value; a missing column gives NaN.

Solution

Show one correct solution (try it yourself first)
def read():
    head = input().split(",")
    rows = [dict(zip(head, input().split(","))) for _ in range(int(input()))]
    return head, rows


a_head, a = read()
b_head, b = read()
cols = a_head + [c for c in b_head if c not in a_head]
print(",".join(cols))
for row in a + b:
    print(",".join(row.get(c) or "NaN" for c in cols))

Lesson: Merging and joining DataFrames →