When pandas reads a file it gives each column one type. Model the rules it uses for the common cases.
What to build
A program that infers the dtype of each column of a comma-separated table.
Requirements
- Empty cells are missing values. For the non-missing cells of a column:
boolif all areTrueorFalse;int64if all are whole numbers;float64if all are numbers (some with a decimal point); otherwiseobject. - An
int64column with at least one missing value becomesfloat64; a column with no values at all isfloat64. Aboolcolumn with a missing value becomesobject. - Print
NAME: DTYPE (M missing)for each column in header order.
Input
Line 1: the header. Line 2: n. Then n rows, values separated by commas.
Output
One line per column.
Constraints
1 ≤ columns ≤ 10; 1 ≤ n ≤ 100; cells contain no commas.
Example
Input:
id,price,name,paid
3
1,9.5,Pen,True
2,,Book,False
3,4,,True
Output:
id: int64 (0 missing)
price: float64 (1 missing)
name: object (1 missing)
paid: bool (0 missing)
Why it works
A column holds one type, and NaN, pandas' missing value, is a float, which is why a single gap turns a whole integer column into floats, and why a missing value in a boolean column falls back to object.
Examples
id,price,name,paid 3 1,9.5,Pen,True 2,,Book,False 3,4,,True
id: int64 (0 missing) price: float64 (1 missing) name: object (1 missing) paid: bool (0 missing)
age,score 2 30, ,
age: float64 (1 missing) score: float64 (2 missing)
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Check every non-empty cell: try int(), then float(), and test for True/False.
Hint 2
An int column with an empty cell becomes float64, because NaN is a float; an all-empty column is float64 too.
Solution
Show one correct solution (try it yourself first)
def is_int(text):
try:
int(text)
return True
except ValueError:
return False
def is_float(text):
try:
float(text)
return True
except ValueError:
return False
header = input().split(",")
n = int(input())
rows = [input().split(",") for _ in range(n)]
for i, name in enumerate(header):
cells = [row[i] for row in rows]
present = [c for c in cells if c != ""]
missing = len(cells) - len(present)
if not present:
dtype = "float64"
elif all(c in ("True", "False") for c in present):
dtype = "object" if missing else "bool"
elif all(is_int(c) for c in present):
dtype = "float64" if missing else "int64"
elif all(is_float(c) for c in present):
dtype = "float64"
else:
dtype = "object"
print(f"{name}: {dtype} ({missing} missing)")