svgtype-composition
Column type composition
What kinds of columns does this dataset hold?
How to read it
- Read the segments as how many columns are of each kind.
- Read the list below for which columns those are.
- Callout 1: Segment size: how many columns of this kind.
- Callout 2: The columns of each kind.
Watch out
- Inferred kinds are guesses. Check the id-like and text groups for columns stored oddly.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Kinds: physical kind (numeric, temporal, categorical, boolean) refined to id-like (all non-missing values distinct, n ≥ 20) and text (long or multi-word strings, > 50 % distinct).
- The profiler's semantic types (email, URL, currency, …) refine these further in Insights.
# Column type composition — Codesplash Chart Lab (recipe "type-composition")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("type-composition-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["signup_date"] = pd.to_datetime(df["signup_date"])
df["last_purchase"] = pd.to_datetime(df["last_purchase"])
df["last_login"] = pd.to_datetime(df["last_login"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])
KIND_ORDER = ["numeric", "temporal", "categorical", "boolean", "text", "id-like"]
KIND_COLOUR = {"numeric": 0, "temporal": 2, "categorical": 1, "boolean": 4, "text": 5, "id-like": 7}
def infer_kind(s, kind):
"""id-like = every non-missing value distinct (n ≥ 20; integers or short strings);
text = strings averaging > 30 characters, or > 3 words with > 50 % distinct."""
if kind in ("boolean", "temporal"):
return kind
present = s.dropna()
distinct = present.astype(str).nunique()
unique = len(present) >= 20 and distinct == len(present)
if kind == "numeric":
ints = bool(np.all(np.mod(present.to_numpy(dtype=float), 1) == 0))
return "id-like" if unique and ints else "numeric"
strs = present.astype(str)
avg_len = strs.str.len().mean() if len(strs) else 0
avg_words = strs.str.strip().str.split().str.len().mean() if len(strs) else 0
if avg_len > 30 or (avg_words > 3 and distinct > 0.5 * len(strs)):
return "text"
return "id-like" if unique else "categorical"
KINDS = {"customer_id": "categorical", "email": "categorical", "signup_date": "temporal", "last_purchase": "temporal", "last_login": "temporal", "age": "numeric", "income": "numeric", "spend_30d": "numeric", "visits_30d": "numeric", "tenure_days": "numeric", "discount_pct": "numeric", "satisfaction": "numeric", "region": "categorical", "plan": "categorical", "device": "categorical", "country": "categorical", "churned": "boolean", "newsletter": "boolean", "mobile_app": "boolean", "comments": "categorical"} # physical kinds from the app
inferred = {n: infer_kind(df[n], k) for n, k in KINDS.items()}
groups = [(k, [n for n, v in inferred.items() if v == k]) for k in KIND_ORDER]
groups = [(k, names) for k, names in groups if names]
fig, (bar, lst) = plt.subplots(2, 1, figsize=(8, 1.2 + 0.45 * len(groups)), gridspec_kw={"height_ratios": [1, len(groups)]})
left = 0
for k, names in groups:
bar.barh(0, len(names), left=left, color=PALETTE[KIND_COLOUR[k]], edgecolor="white")
bar.text(left + len(names) / 2, 0, str(len(names)), ha="center", va="center", color="white", fontsize=9, fontweight="bold")
left += len(names)
bar.set_xlim(0, len(KINDS))
bar.axis("off")
bar.set_title(f"{len(KINDS)} columns", fontsize=9, loc="left")
for i, (k, names) in enumerate(groups):
lst.text(0, -i, f"{k} ({len(names)})", color=PALETTE[KIND_COLOUR[k]], fontsize=9, va="center")
lst.text(0.22, -i, ", ".join(names), fontsize=8, va="center")
lst.set_ylim(-len(groups) + 0.5, 0.5)
lst.axis("off")
plt.show()Needs pandas, numpy, matplotlib · reads type-composition-demo.csv · app theme from the optional codesplash helper
# Column type composition — Codesplash Chart Lab (recipe "type-composition")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("type-composition-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["signup_date"] = pd.to_datetime(df["signup_date"])
df["last_purchase"] = pd.to_datetime(df["last_purchase"])
df["last_login"] = pd.to_datetime(df["last_login"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])
KIND_ORDER = ["numeric", "temporal", "categorical", "boolean", "text", "id-like"]
KIND_COLOUR = {"numeric": 0, "temporal": 2, "categorical": 1, "boolean": 4, "text": 5, "id-like": 7}
def infer_kind(s, kind):
"""id-like = every non-missing value distinct (n ≥ 20; integers or short strings);
text = strings averaging > 30 characters, or > 3 words with > 50 % distinct."""
if kind in ("boolean", "temporal"):
return kind
present = s.dropna()
distinct = present.astype(str).nunique()
unique = len(present) >= 20 and distinct == len(present)
if kind == "numeric":
ints = bool(np.all(np.mod(present.to_numpy(dtype=float), 1) == 0))
return "id-like" if unique and ints else "numeric"
strs = present.astype(str)
avg_len = strs.str.len().mean() if len(strs) else 0
avg_words = strs.str.strip().str.split().str.len().mean() if len(strs) else 0
if avg_len > 30 or (avg_words > 3 and distinct > 0.5 * len(strs)):
return "text"
return "id-like" if unique else "categorical"
KINDS = {"customer_id": "categorical", "email": "categorical", "signup_date": "temporal", "last_purchase": "temporal", "last_login": "temporal", "age": "numeric", "income": "numeric", "spend_30d": "numeric", "visits_30d": "numeric", "tenure_days": "numeric", "discount_pct": "numeric", "satisfaction": "numeric", "region": "categorical", "plan": "categorical", "device": "categorical", "country": "categorical", "churned": "boolean", "newsletter": "boolean", "mobile_app": "boolean", "comments": "categorical"} # physical kinds from the app
inferred = {n: infer_kind(df[n], k) for n, k in KINDS.items()}
fig = go.Figure()
for k in KIND_ORDER:
names = [n for n, v in inferred.items() if v == k]
if names:
fig.add_bar(y=["columns"], x=[len(names)], orientation="h", name=f"{k} ({len(names)})", marker_color=PALETTE[KIND_COLOUR[k]], text=[len(names)], hovertext=", ".join(names), hoverinfo="text")
fig.update_layout(barmode="stack", height=220, title=f"{len(KINDS)} columns", yaxis_visible=False)
fig.show()Needs pandas, numpy, plotly · reads type-composition-demo.csv · app theme from the optional codesplash helper
# Column type composition — Codesplash Chart Lab (recipe "type-composition")
# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("type-composition-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["signup_date"]] <- as.POSIXct(df[["signup_date"]], tz = "UTC")
df[["last_purchase"]] <- as.POSIXct(df[["last_purchase"]], tz = "UTC")
df[["last_login"]] <- as.POSIXct(df[["last_login"]], tz = "UTC")
df[["churned"]] <- as.logical(df[["churned"]])
df[["newsletter"]] <- as.logical(df[["newsletter"]])
df[["mobile_app"]] <- as.logical(df[["mobile_app"]])
df[["customer_id"]] <- factor(df[["customer_id"]])
df[["email"]] <- factor(df[["email"]])
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
df[["plan"]] <- factor(df[["plan"]], levels = c("Basic", "Plus", "Pro"))
df[["device"]] <- factor(df[["device"]])
df[["country"]] <- factor(df[["country"]])
df[["comments"]] <- factor(df[["comments"]])
kind_order <- c("numeric", "temporal", "categorical", "boolean", "text", "id-like")
kind_colour <- c(numeric = 1, temporal = 3, categorical = 2, boolean = 5, text = 6, "id-like" = 8)
infer_kind <- function(v, kind) {
# id-like = every non-missing value distinct (n >= 20); text = long or multi-word strings, > 50 % distinct
if (kind %in% c("boolean", "temporal")) return(kind)
present <- v[!is.na(v)]
distinct <- length(unique(as.character(present)))
unique_all <- length(present) >= 20 && distinct == length(present)
if (kind == "numeric") return(if (unique_all && all(present %% 1 == 0)) "id-like" else "numeric")
s <- as.character(present)
avg_len <- if (length(s)) mean(nchar(s)) else 0
avg_words <- if (length(s)) mean(lengths(strsplit(trimws(s), "\\s+"))) else 0
if (avg_len > 30 || (avg_words > 3 && distinct > 0.5 * length(s))) return("text")
if (unique_all) "id-like" else "categorical"
}
kinds <- c("customer_id" = "categorical", "email" = "categorical", "signup_date" = "temporal", "last_purchase" = "temporal", "last_login" = "temporal", "age" = "numeric", "income" = "numeric", "spend_30d" = "numeric", "visits_30d" = "numeric", "tenure_days" = "numeric", "discount_pct" = "numeric", "satisfaction" = "numeric", "region" = "categorical", "plan" = "categorical", "device" = "categorical", "country" = "categorical", "churned" = "boolean", "newsletter" = "boolean", "mobile_app" = "boolean", "comments" = "categorical") # physical kinds from the app
inferred <- vapply(names(kinds), function(n) infer_kind(df[[n]], kinds[[n]]), character(1))
groups <- data.frame(kind = factor(inferred, levels = kind_order), column = names(inferred))
counts <- as.data.frame(table(kind = groups$kind)); counts <- counts[counts$Freq > 0, ]
counts$names <- vapply(as.character(counts$kind), function(k) paste(groups$column[groups$kind == k], collapse = ", "), character(1))
p <- ggplot(counts, aes(x = "columns", y = Freq, fill = kind)) +
geom_col(position = position_stack(reverse = TRUE), colour = "white") +
geom_text(aes(label = Freq), position = position_stack(vjust = 0.5, reverse = TRUE), colour = "white", fontface = "bold") +
scale_fill_manual(values = stats::setNames(cs_cat[kind_colour[kind_order]], kind_order),
labels = function(k) paste0(k, ": ", counts$names[match(k, counts$kind)])) +
coord_flip() +
labs(x = NULL, y = NULL, fill = NULL, title = sprintf("%d columns", length(inferred))) +
theme_cs + theme(legend.position = "bottom", legend.direction = "vertical", axis.text = element_blank(), panel.grid = element_blank())
print(p)Needs ggplot2 · reads type-composition-demo.csv · app theme from the optional codesplashr helper
-- Column type composition — Codesplash Chart Lab (recipe "type-composition")
-- controls: defaults
-- inferred kind per column: physical kind refined to id-like (all distinct, n ≥ 20) and text
SELECT 'customer_id' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("customer_id"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("customer_id"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "customer_id") > 0.5 * count("customer_id")) THEN 'text'
WHEN count("customer_id") >= 20 AND count(DISTINCT "customer_id") = count("customer_id") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'email' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("email"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("email"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "email") > 0.5 * count("email")) THEN 'text'
WHEN count("email") >= 20 AND count(DISTINCT "email") = count("email") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'signup_date' AS "column", 'temporal' AS physical,
'temporal' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'last_purchase' AS "column", 'temporal' AS physical,
'temporal' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'last_login' AS "column", 'temporal' AS physical,
'temporal' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'age' AS "column", 'numeric' AS physical,
CASE WHEN count("age") >= 20 AND count(DISTINCT "age") = count("age") AND bool_and("age" = round("age")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'income' AS "column", 'numeric' AS physical,
CASE WHEN count("income") >= 20 AND count(DISTINCT "income") = count("income") AND bool_and("income" = round("income")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'spend_30d' AS "column", 'numeric' AS physical,
CASE WHEN count("spend_30d") >= 20 AND count(DISTINCT "spend_30d") = count("spend_30d") AND bool_and("spend_30d" = round("spend_30d")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'visits_30d' AS "column", 'numeric' AS physical,
CASE WHEN count("visits_30d") >= 20 AND count(DISTINCT "visits_30d") = count("visits_30d") AND bool_and("visits_30d" = round("visits_30d")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'tenure_days' AS "column", 'numeric' AS physical,
CASE WHEN count("tenure_days") >= 20 AND count(DISTINCT "tenure_days") = count("tenure_days") AND bool_and("tenure_days" = round("tenure_days")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'discount_pct' AS "column", 'numeric' AS physical,
CASE WHEN count("discount_pct") >= 20 AND count(DISTINCT "discount_pct") = count("discount_pct") AND bool_and("discount_pct" = round("discount_pct")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'satisfaction' AS "column", 'numeric' AS physical,
CASE WHEN count("satisfaction") >= 20 AND count(DISTINCT "satisfaction") = count("satisfaction") AND bool_and("satisfaction" = round("satisfaction")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'region' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("region"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("region"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "region") > 0.5 * count("region")) THEN 'text'
WHEN count("region") >= 20 AND count(DISTINCT "region") = count("region") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'plan' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("plan"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("plan"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "plan") > 0.5 * count("plan")) THEN 'text'
WHEN count("plan") >= 20 AND count(DISTINCT "plan") = count("plan") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'device' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("device"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("device"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "device") > 0.5 * count("device")) THEN 'text'
WHEN count("device") >= 20 AND count(DISTINCT "device") = count("device") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'country' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("country"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("country"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "country") > 0.5 * count("country")) THEN 'text'
WHEN count("country") >= 20 AND count(DISTINCT "country") = count("country") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'churned' AS "column", 'boolean' AS physical,
'boolean' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'newsletter' AS "column", 'boolean' AS physical,
'boolean' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'mobile_app' AS "column", 'boolean' AS physical,
'boolean' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'comments' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("comments"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("comments"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "comments") > 0.5 * count("comments")) THEN 'text'
WHEN count("comments") >= 20 AND count(DISTINCT "comments") = count("comments") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv');Needs duckdb · reads type-composition-demo.csv