Module 19: pandas¶
Learning objectives
By the end of this module, you can:
- O1. Read a DDI file into pandas with
to_dataframes, and say what thenodes,membershipsandrelationshipstables hold. - O2. Pick the nodes of one type, with only the columns that type uses, with
frames.of(label). - O3. Join the tables with
mergeto build a table of variables with their questions, and a table of a code list's categories. - O4. Write the tables to CSV files and to an Excel workbook, with each list joined into one string.
Prerequisites: Module 5
Time: 35 min self-paced / 50 min instructor-led.
Needs: No server. The pandas extra, which also installs openpyxl for Excel (pip install "ddigraph[pandas]").
New in this module: ddigraph.backends.pandas.to_dataframes, GraphFrames,
frames.nodes, frames.memberships, frames.relationships, frames.of(),
DataFrame.merge, DataFrame.explode, DataFrame.to_csv, pd.ExcelWriter
1. A graph in three tables¶
pandas is Python's library for tables. A table in pandas is a DataFrame: rows and named columns, like a spreadsheet. Use it when the next step is a report, a spreadsheet, or a join with other data.
This module works on the course's sample survey, a Labour Force Survey of the third quarter
of 2025. tests/fixtures/lfs_codebook.xml holds it in DDI-Codebook, and
tests/fixtures/lfs_lifecycle.xml in DDI-Lifecycle 3.3.
A graph does not fit in one table. A node and a relationship have different columns, and a
node can belong to several datasets. So to_dataframes gives three tables, in a
GraphFrames object:
nodes: one row per node;memberships: one row per node and dataset that holds it;relationships: one row per edge.
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
print("nodes:", frames.nodes.shape)
print("memberships:", frames.memberships.shape)
print("relationships:", frames.relationships.shape)
print()
print(frames.memberships.head(3).to_string(index=False))
print()
print(frames.relationships.head(3).to_string(index=False))
Expected output:
nodes: (80, 20)
memberships: (79, 5)
relationships: (48, 5)
key dataset_id source flavor line
0159ff8be20b8108129e4e5860656501 lfs_codebook tests/fixtures/lfs_codebook.xml codebook 25
056ea6bea0ae25b08799f86c26c0bb6e lfs_codebook tests/fixtures/lfs_codebook.xml codebook 53
06e55574fc8a2939e1ba7778f7ffbce1 lfs_codebook tests/fixtures/lfs_codebook.xml codebook 6
start type end ordinal resolution
06e55574fc8a2939e1ba7778f7ffbce1 DESCRIBES e305dcb613c48db3d612b97dd8a24801 None None
1b42f30df5c45cd690244c8f530dd342 COVERS e305dcb613c48db3d612b97dd8a24801 None None
25b8ca1d91e1b13c4124216d9ad56d0d ASSOCIATED_WITH e305dcb613c48db3d612b97dd8a24801 None None
.shape gives (rows, columns). Read the tables:
nodeshas 80 rows, one per node, and 20 columns.keynames the node, 32 hex characters, the same in every backend.node_labelsis its types, as a list.identityis its identity as text. The other columns are properties. Different types have different properties, so most cells in a row are empty.membershipshas 79 rows: every node but the Dataset node, which stands for the file. Each row says which dataset holds the node, and the file, flavor and line it came from. It plays the part of Neo4j'sIN_DATASETedges.relationshipshas one row per edge.startandendare node keys.ordinalis the edge's place in an ordered list, andresolutionsays how a reference found its end.
Every column holds Python objects, and None marks a missing value. The
pandas backend page lists every column.
node_labels holds a list per row. To count nodes by type, explode() first: it gives one
row per item of each list. Then value_counts() counts them:
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
types = frames.nodes["node_labels"].explode().value_counts().reset_index()
top = types.sort_values(["count", "node_labels"], ascending=[False, True]).head(5)
print(top.to_string(index=False))
Expected output:
node_labels count
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5
The sort puts the largest counts first and breaks ties by name, so the order never changes. The Neo4j recipe of Module 17 gives the same counts for this file.
Read the counts as a survey. The 21 categories are the answers of the five coded variables. There are 7 concepts, though the survey has only 5: DDI-Codebook writes the concept inside each variable, so "Demographic characteristics" is a node for each of SEX, AGE and AGEGRP. DDI-Lifecycle would give one concept node, reused three times.
2. One type at a time¶
frames.nodes has every column any type uses. frames.of(label) keeps the rows of one type,
and drops each column that is empty for all of them:
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
variables = frames.of("Variable").sort_values("ddi_id")
print(variables.columns.tolist())
print(variables[["ddi_id", "name", "label", "question_text"]].to_string(index=False))
Expected output:
['key', 'node_labels', 'identity', 'dataset_id', 'ddi_id', 'label', 'name', 'question_text']
ddi_id name label question_text
V1 SEX Sex of the person What is your sex?
V2 AGE Age in completed years What was your age on your last birthday?
V3 AGEGRP Age group None
V4 REGION Region of residence In which region do you live?
V5 EDUC Highest level of education What is the highest level of education you have completed?
V6 ILOSTAT Labour force status (ILO) None
V7 HOURS Usual weekly hours in the main job How many hours a week do you usually work in your main job?
Eight columns, not 20. This is the start of a data dictionary: each variable's name, its
label, and the question that collects it. sort_values("ddi_id") puts the variables in the
order of the file.
A column stays when at least one variable has a value. So question_text is kept, though
AGEGRP and ILOSTAT have none. They are derived variables: AGEGRP is grouped from AGE,
and ILOSTAT is worked out from three questions. Nobody is asked them.
3. Join the tables: variables with their questions¶
The tables link through keys. A relationship names its two ends in start and end, and
each end is the key of a row of nodes. To follow an edge, merge: join two tables on
columns that hold the same values.
In a Codebook file, a variable points at its question with ASKED_AS. This block builds a
table of each variable with its question node:
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
variables = frames.of("Variable")[["key", "name"]]
questions = frames.of("Question")[["key", "ddi_id", "question_text"]]
asked = frames.relationships[frames.relationships["type"] == "ASKED_AS"]
table = variables.merge(asked, left_on="key", right_on="start", how="left").merge(
questions, left_on="end", right_on="key", how="left", suffixes=("", "_question")
)
print(table[["name", "ddi_id", "question_text"]].sort_values("name").to_string(index=False))
Expected output:
name ddi_id question_text
AGE Q-AGE What was your age on your last birthday?
AGEGRP NaN NaN
EDUC Q-EDUC What is the highest level of education you have completed?
HOURS Q-HOURS How many hours a week do you usually work in your main job?
ILOSTAT NaN NaN
REGION Q-REGION In which region do you live?
SEX Q-SEX What is your sex?
Read it step by step:
askedkeeps the edges of one type.- The first
mergejoins each variable'skeyto an edge'sstart.how="left"keeps every variable, even one with no edge. Without it, AGEGRP and ILOSTAT would vanish. - The second
mergejoins each edge'sendto a question'skey, to bring in the question.suffixesrenames the secondkeycolumn, so the two do not clash.
NaN marks a cell the left merge had nothing to fill. Here it marks the two derived
variables, which have no question.
A join gives one row per match. In this file, each asked variable has one question. In the DDI-Lifecycle file, ILOSTAT refers to the three questions it comes from, WORK, LOOK and AVAIL, so the same join would give it three rows.
The same idea answers another question: which concept does each variable use? Here it is in pandas and in NetworkX, which Module 18 teaches. Pick a tab, and the site remembers it for every code box.
from ddigraph.backends.networkx import to_networkx
G = to_networkx("tests/fixtures/lfs_codebook.xml")
rows = [
(G.nodes[start]["name"], G.nodes[end]["label"])
for start, end, (rel_type, _ordinal) in G.edges(keys=True)
if rel_type == "USES_CONCEPT" and "Variable" in G.nodes[start]["node_labels"]
]
for variable, concept in sorted(rows):
print(variable, "|", concept)
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics
Module 18 builds this graph. An edge already knows its two nodes, so there is no join.
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
variables = frames.of("Variable")[["key", "name"]]
concepts = frames.of("Concept")[["key", "label"]]
uses = frames.relationships[frames.relationships["type"] == "USES_CONCEPT"]
table = (
uses.merge(variables, left_on="start", right_on="key")
.merge(concepts, left_on="end", right_on="key")
.sort_values("name")
)
for row in table.itertuples():
print(row.name, "|", row.label)
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics
Two merges: the relationship's start to the variable's key, and its end to the
concept's.
Same seven rows. Choose NetworkX to walk a graph, and pandas when the next step is a table: a report, a spreadsheet, or a join with your own data.
4. A code-list table¶
DDI-Lifecycle keeps code lists apart from the questions that use them. A question points at
its code list with USES_CODELIST. The list CONTAINS its codes, and each code points at
its category with HAS_CATEGORY. So a code-list table takes three edges.
edges() below is a small helper. It keeps the edges of one type, and renames start and
end after what they point at, so each merge reads like the path it follows:
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_lifecycle.xml")
rels = frames.relationships
questions = frames.of("QuestionItem")[["key", "name"]]
nodes = frames.nodes[["key", "label", "value"]]
def edges(rel_type, start, end):
# The edges of one type, with their ends named
found = rels[rels["type"] == rel_type]
return found[["start", "end", "ordinal"]].rename(columns={"start": start, "end": end})
uses = edges("USES_CODELIST", "question", "code_list")[["question", "code_list"]]
contains = edges("CONTAINS", "code_list", "code")
has = edges("HAS_CATEGORY", "code", "category")[["code", "category"]]
table = (
uses.merge(contains, on="code_list")
.merge(has, on="code")
.merge(questions, left_on="question", right_on="key")
.merge(nodes[["key", "label"]], left_on="code_list", right_on="key")
.merge(nodes[["key", "value"]], left_on="code", right_on="key")
.merge(nodes[["key", "label"]], left_on="category", right_on="key", suffixes=("_list", ""))
.sort_values(["name", "ordinal"])
)
columns = ["name", "label_list", "value", "label"]
print(table[table["name"].isin(["EDUC", "LOOK", "WORK"])][columns].to_string(index=False))
Expected output:
name label_list value label
EDUC Highest level of education 1 Primary or less (ISCED 0-1)
EDUC Highest level of education 2 Lower secondary (ISCED 2)
EDUC Highest level of education 3 Upper secondary (ISCED 3)
EDUC Highest level of education 4 Post-secondary non-tertiary (ISCED 4)
EDUC Highest level of education 5 Tertiary (ISCED 5-8)
LOOK Yes or no 1 Yes
LOOK Yes or no 2 No
WORK Yes or no 1 Yes
WORK Yes or no 2 No
This is the code-list part of a data dictionary: each question, its code list, and each
code with its category. The ordinal of CONTAINS is the code's place in the list, from 0,
so sorting on it keeps the list's own order. Variables point at code lists too, so the
merge with questions keeps only the rows that start at a question. The block prints three
of the six coded questions, to keep the output short.
WORK and LOOK use the same list, "Yes or no", and so does AVAIL. DDI-Lifecycle writes the list once and reuses it. A Codebook file would repeat the two categories under each variable.
A DDI 3.1 file can hold codes with no ID. Such a code is not a node, and its category hangs
off the code list itself. In Cypher, [:CONTAINS*0..1] covers both kinds. In pandas, you
would add each code list as its own "code", with pd.concat, before the merge.
5. Write CSV and Excel¶
A CSV cell holds one value, and so does a spreadsheet cell. So join each list of type labels
into one string with | first. .str.join("|") does that for a whole column:
import pandas as pd
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
nodes = frames.nodes.assign(node_labels=frames.nodes["node_labels"].str.join("|"))
nodes.to_csv("nodes.csv", index=False)
frames.memberships.to_csv("memberships.csv", index=False)
frames.relationships.to_csv("relationships.csv", index=False)
back = pd.read_csv("nodes.csv")
print(back.shape)
variables = back.loc[back["node_labels"] == "Variable", ["ddi_id", "name", "label"]]
print(variables.sort_values("ddi_id").to_string(index=False))
Expected output:
(80, 20)
ddi_id name label
V1 SEX Sex of the person
V2 AGE Age in completed years
V3 AGEGRP Age group
V4 REGION Region of residence
V5 EDUC Highest level of education
V6 ILOSTAT Labour force status (ILO)
V7 HOURS Usual weekly hours in the main job
index=False leaves out pandas' row numbers. Reading the file back gives the same 80 rows
and 20 columns. Since node_labels is now a plain string, == "Variable" finds the
variables.
An Excel workbook can hold all three tables, one per sheet. pandas writes .xlsx files
through openpyxl, which the pandas extra installs. This block writes the workbook, then
opens it with openpyxl to list its sheets:
import openpyxl
import pandas as pd
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
nodes = frames.nodes.assign(node_labels=frames.nodes["node_labels"].str.join("|"))
with pd.ExcelWriter("codebook.xlsx") as writer:
nodes.to_excel(writer, sheet_name="nodes", index=False)
frames.memberships.to_excel(writer, sheet_name="memberships", index=False)
frames.relationships.to_excel(writer, sheet_name="relationships", index=False)
workbook = openpyxl.load_workbook("codebook.xlsx")
for sheet in workbook.worksheets:
print(sheet.title, sheet.max_row - 1, "rows,", sheet.max_column, "columns")
Expected output:
nodes 80 rows, 20 columns
memberships 79 rows, 5 columns
relationships 48 rows, 5 columns
max_row counts the header row too, hence the - 1. ddigraph export --format csv writes
similar tables from the command line, with each node's type as one string. See the
CLI reference.
Exercises¶
Scenario
A methodologist wants the Labour Force Survey's metadata in a spreadsheet, to check it by eye. She asks for a few tables she can open in Excel.
Exercise 1 (O1, O2). For tests/fixtures/lfs_codebook.xml, print each variable's
name with the dataset, flavor and line it came from, in the order of the file. Take the
variables with of(), and the rest from memberships.
Expected output:
name dataset_id flavor line
SEX lfs_codebook codebook 43
...
Answer
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
variables = frames.of("Variable")[["key", "name"]]
placed = variables.merge(frames.memberships, on="key").sort_values("line")
print(placed[["name", "dataset_id", "flavor", "line"]].to_string(index=False))
name dataset_id flavor line
SEX lfs_codebook codebook 43
AGE lfs_codebook codebook 52
AGEGRP lfs_codebook codebook 60
REGION lfs_codebook codebook 73
EDUC lfs_codebook codebook 85
ILOSTAT lfs_codebook codebook 97
HOURS lfs_codebook codebook 107
Both tables have a key column, so on="key" joins them. Where a node comes from is
in memberships, not in nodes, since one node can come from several files. The
line is where the variable starts in the file, so sorting on it gives the file's order.
Exercise 2 (O3). tests/fixtures/lfs_cdi.xml is the same survey in DDI-CDI. There, a
code list HAS_CODE codes. Each code USES a notation, which holds the code's value,
and DENOTES a category. Build a table of the code list "Labour force status (ILO)": each
code's value with the name of its category, in the order of the values.
Expected output:
value name
1 Employed
...
Answer
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_cdi.xml")
rels = frames.relationships
nodes = frames.nodes[["key", "name", "value"]]
def edges(rel_type, start, end):
# The edges of one type, with their ends named
found = rels[rels["type"] == rel_type]
return found[["start", "end"]].rename(columns={"start": start, "end": end})
lists = frames.of("CDICodeList")
ilo = lists.loc[lists["name"] == "Labour force status (ILO)", ["key"]]
table = (
ilo.merge(edges("HAS_CODE", "key", "code"), on="key")
.merge(edges("USES", "code", "notation"), on="code")
.merge(edges("DENOTES", "code", "category"), on="code")
.merge(nodes[["key", "value"]], left_on="notation", right_on="key")
.merge(nodes[["key", "name"]], left_on="category", right_on="key")
.sort_values("value")
)
print(table[["value", "name"]].to_string(index=False))
value name
1 Employed
2 Unemployed
3 Not in the labour force
Four merges walk the path: the list to its codes, each code to its notation and to its category, then the two ends to the nodes that hold the value and the name. The table starts from one row, the code list, so it keeps only that list's codes. The three categories cover everyone aged 15 and over: each person is in exactly one.
Exercise 3 (O3, O4). For tests/fixtures/lfs_lifecycle.xml, build a table of each
variable's name and label with the label of its concept. Write it to variables.csv, and
print the file.
Expected output:
name,label,label_concept
AGE,Age in completed years,Demographic characteristics
...
Answer
from pathlib import Path
from ddigraph.backends.pandas import to_dataframes
frames = to_dataframes("tests/fixtures/lfs_lifecycle.xml")
variables = frames.of("Variable")[["key", "name", "label"]]
concepts = frames.of("Concept")[["key", "label"]]
uses = frames.relationships[frames.relationships["type"] == "USES_CONCEPT"]
table = (
uses.merge(variables, left_on="start", right_on="key")
.merge(concepts, left_on="end", right_on="key", suffixes=("", "_concept"))
.sort_values("name")
)
table[["name", "label", "label_concept"]].to_csv("variables.csv", index=False)
print(Path("variables.csv").read_text(encoding="utf-8"), end="")
name,label,label_concept
AGE,Age in completed years,Demographic characteristics
AGEGRP,Age group,Demographic characteristics
EDUC,Highest level of education,Educational attainment
HOURS,Usual weekly hours in the main job,Working time
ILOSTAT,Labour force status (ILO),Labour market status
REGION,Region of residence,Place of residence
SEX,Sex of the person,Demographic characteristics
In DDI-Lifecycle, questions use concepts too. The merge with variables keeps only
the edges that start at a variable. Three variables share the one concept node
"Demographic characteristics". Keeping only the columns a reader needs makes a table
someone can check by eye. The keys stay out: they join the tables, but mean nothing to
a person.
Quiz¶
Question 1 (O1): Why does to_dataframes give three tables instead of one?
A. pandas cannot hold more than 20 columns in one table.
B. A node, a membership and an edge have different columns, and a node can belong to several datasets. One table would need a row for each mix.
C. Each table comes from a different file.
D. The three tables hold three different graphs.
Answer
B. A graph does not fit in one rectangle. The three tables join on key,
start and end, so you rebuild any view you need with merge.
Question 2 (O1): Why does the type count call explode() before value_counts()?
A. node_labels holds a list per row. explode() gives one row per item, so each
type is counted on its own.
B. explode() removes empty rows.
C. value_counts() only works on numbers.
D. explode() sorts the types.
Answer
A. Without it, pandas would count each whole list as one value, so a node with two types would count as a type of its own. Most nodes have one type, which makes this easy to miss.
Question 3 (O2): frames.of("Variable") keeps the column question_text, but AGEGRP and ILOSTAT have no question. Why is it kept?
A. of() keeps every column of frames.nodes.
B. question_text is always kept.
C. of() drops a column only when it is empty for every row of that type. The five
asked variables have a value, and one is enough to keep it.
D. It is a bug.
Answer
C. of() drops a column only when it is empty for all the rows of the type. So
frames.of("Variable") has 8 columns, not 20, and still keeps question_text. The
two derived variables show None in it.
Question 4 (O3): You merge the variables with the ASKED_AS edges, and AGEGRP and ILOSTAT disappear from the result. What happened?
A. The file holds no such variables.
B. A plain merge keeps only rows that match on both sides. AGEGRP and ILOSTAT are
derived, so they have no ASKED_AS edge, and they drop out. how="left" keeps them.
C. merge removes duplicate labels.
D. The edges point the other way.
Answer
B. merge is an inner join by default. A left join keeps every row of the left
table, and fills the cells it cannot match with NaN.
Question 5 (O4): You write frames.nodes to CSV as it is, and the node_labels column holds text like ['Variable']. What should you do?
A. Nothing: CSV keeps lists.
B. Drop the column.
C. Write to JSON instead; CSV cannot hold types.
D. Join each list into one string first, with
frames.nodes["node_labels"].str.join("|").
Answer
D. A CSV cell holds one value. pandas writes a list as its Python text, which
another tool cannot split reliably. Joined with |, it reads back as a plain string,
and splits again with .str.split("|").
Question 6 (O4): to_excel fails with "Missing optional dependency 'openpyxl'". What is the fix?
A. Save as CSV and rename the file .xlsx.
B. Install the pandas extra, pip install "ddigraph[pandas]", which brings
openpyxl.
C. Install matplotlib.
D. Write each table to its own workbook.
Answer
B. pandas writes .xlsx files through openpyxl. A renamed CSV file is not a
workbook: Excel would warn, and the sheets would be lost.
Check yourself¶
- I can read a DDI file into pandas with
to_dataframes, and say what thenodes,membershipsandrelationshipstables hold. (O1) - I can pick the nodes of one type, with only the columns that type uses, with
frames.of(label). (O2) - I can join the tables with
mergeto build a table of variables with their questions, and a table of a code list's categories. (O3) - I can write the tables to CSV files and to an Excel workbook, with each list joined into one string. (O4)