Preprocessing Data
Python, from raw text to structured data, and preparing data for analysis.
- Entry
- No. 002
- Part
- Workflow, step 2 of 4
Record of the painting
- Artist
- Ignacio Díaz Olano (1860–1937)
- Title
- Las planchadoras (The Ironing Women)
- Date
- 1895
- Medium
- Oil on canvas, 90 × 142 cm
- Collection
- Museo de Bellas Artes de Álava, Vitoria-Gasteiz (Diputación Foral de Álava)
- Number
- Inv. 3390
- Rights
- Public domain.
- Image
- Museo de Bellas Artes de Álava, via Museotik
Provenance
Acquired by Felipe Arrieta, Vitoria, 1895; collection of María Luisa Gortázar, Vitoria; collection of Juan Celaya Letamendi, Vitoria-Gasteiz; deposited by the Fundación Juan Celaya Letamendi with the Diputación Foral de Álava, 2018; transferred to the Diputación Foral de Álava in payment of tax debts (dación), 2022
| Date | Event | Holder | Place |
|---|---|---|---|
| 1895 | Acquisition | Felipe Arrieta | Vitoria |
| — | Collection | María Luisa Gortázar | Vitoria |
| — | Collection | Juan Celaya Letamendi | Vitoria-Gasteiz |
| 2018 | Deposit | Fundación Juan Celaya Letamendi, with the Diputación Foral de Álava | Vitoria-Gasteiz |
| 2022 | Payment in kind of tax debts (dación) | Diputación Foral de Álava | Vitoria-Gasteiz |
Translated from the holding museum's record: Museotik, Las planchadoras.
Python
Agenda
What is Python?
Understanding Python as a Language
Why Generative AI is Helpful for Coding Purposes
Writing Good Prompts
How Large Language Models Work
Slides
Other coding environments
Resources
- Google Colab
- Visual Studio Code
- Programming Historian
- Python Documentation
- Python Official Website
- Word Embedding Demo — An interactive demo that shows how a computer turns words into numbers, so that words with similar meanings sit close together
- Map of English Wikipedia — A Nomic Atlas map of Wikipedia in which every dot is a piece of text and similar texts sit close together
From raw text to structured data
Agenda
Data Structure
Natural Language Processing
Slides
Datasets
Raw text to data datasets
The provenance records we work with in this session, including 2_momi_subset.csv. Download them before you start the exercises.
Code
Upload the CSV and load it with pandas
We work in Google Colab. Before running the code, upload the dataset to your notebook: download 2_momi_subset.csv from the datasets folder above, click the folder icon in Colab’s left sidebar, then the upload icon, and choose the file. Colab deletes uploaded files when the session ends, so upload it again if you come back later.
The code imports pandas, a Python library for working with tables, under the short name pd. It then reads the CSV into a table called df (short for DataFrame, pandas’ name for a table) and shows its first five rows.
# Load pandas, the library for working with tables, under the short name pd
import pandas as pd
# Read the uploaded CSV file into a table called df
df = pd.read_csv("2_momi_subset.csv")
# Show the first five rows to check that the file loaded correctly
df.head()Make a subset with the ID and the provenance
The table has many columns, but for this exercise we only need two: MOMI_id, which identifies each artwork, and provenance, the text we will turn into structured data. We keep just those two in a new, smaller table called subset, so we can always trace each provenance text back to its artwork through its ID.
# Pick the two columns we need, by name, from the full table df.
# .copy() makes subset a separate table, so changing it later leaves df untouched.
subset = df[["MOMI_id", "provenance"]].copy()
# Show the first five rows to check the result
subset.head()Split each provenance text into events
A provenance text lists the owners of a work one after the other. Each owner or change of hands is one event, and events are separated by a semicolon (the work passed directly to the next owner) or a full stop (there is a gap in what we know). We cut the text at every ; and ., but not at the full stops of abbreviations such as M., Co. or Feb.: spaCy’s tokenizer recognizes these and keeps them inside the event. First we remove HTML tags and the notes in square brackets, which have full stops of their own.
Every event gets an id built from the MoMI id, so it is unique and can always be traced back to its artwork: MOMI_854_E01, MOMI_854_E02 and so on.
import re
import spacy
# A blank English model: it only cuts text into words and knows abbreviations such as "Co." and "Feb."
tokenizer = spacy.blank("en")
# Remove the parts of the text that are not provenance events
def clean(text):
text = re.sub(r"<[^>]+>", "", text) # HTML tags, e.g. <i>
text = re.sub(r"\[[^\]]*\]", "", text) # notes in square brackets, e.g. [1] or [Joyant 1926]
text = text.replace("’", "'") # curly apostrophe -> straight, e.g. Christie's
return re.sub(r"\s+", " ", text).strip() # double spaces -> one space
# Cut one provenance text into events at every ";" and "." that stands on its own
def split_into_events(text):
events, current = [], ""
for token in tokenizer(clean(text)):
if token.text in (";", "."): # end of an event
events.append(current)
current = ""
else:
current += token.text_with_ws # keep adding words to the current event
events.append(current)
return [e.strip(" ,") for e in events if e.strip(" ,")] # drop empty pieces
# One row per event, with an id built from the MoMI id: MOMI_854_E01, MOMI_854_E02 ...
rows = []
for _, record in subset.iterrows():
for n, text in enumerate(split_into_events(record["provenance"]), start=1):
rows.append({
"MOMI_id": record["MOMI_id"],
"prov_event_id": f"{record['MOMI_id']}_E{n:02d}",
"event_text": text,
})
events = pd.DataFrame(rows)
eventsCheck the events for cutting mistakes
The computer cuts at every full stop it does not recognize as an abbreviation, so some events are cut in the wrong place. Three signs point to a mistake: an event of only one or two words, a bracket that opens and does not close, and an event that starts with a number. This cell adds a check column and shows only the events that need a look. Read each one next to the original provenance text before deciding what to do.
In this dataset it finds four pieces: stock no. was taken for the end of an event.
# Signs that an event may have been cut in the wrong place
def check_event(text):
problems = []
if len(text.split()) < 3: # fewer than three words
problems.append("very short")
if text.count("(") != text.count(")"): # a "(" without its ")"
problems.append("bracket not closed")
if text[0].isdigit(): # first character is a number
problems.append("starts with a number")
return ", ".join(problems) # empty when nothing looks wrong
# Run the checks on every event and write the result in a new column
events["check"] = events["event_text"].apply(check_event)
# Show only the events that need a look
events[events["check"] != ""]Fix the events
Write the ids of the events that were cut too early in join_with_next: each one is joined to the piece that follows it. Write any text you want to correct by hand in corrections. The two lists below hold the fixes for this dataset; for your own data, replace them with yours. The ids are then numbered again so they have no gaps, and the check column should now be empty.
# Events that were cut too early: each one is joined to the event that follows it
join_with_next = ["MOMI_1310_E01", "MOMI_1310_E04"]
# Events whose text you want to correct by hand: "event id": "corrected text"
corrections = {
"MOMI_854_E04": "sold to M. Knoedler & Co., 23 July 1929, until 1937", # the source repeats "23"
}
fixed = events.copy() # work on a copy, so this cell can be run again safely
for event_id in join_with_next:
i = fixed.index[fixed["prov_event_id"] == event_id][0] # row of the event
fixed.loc[i, "event_text"] += ". " + fixed.loc[i + 1, "event_text"] # add back the "." and the next piece
fixed = fixed.drop(index=i + 1) # remove the piece we just joined
for event_id, text in corrections.items():
fixed.loc[fixed["prov_event_id"] == event_id, "event_text"] = text
# Number the events again so the ids have no gaps: MOMI_1310_E01, _E02, _E03 ...
fixed = fixed.reset_index(drop=True)
fixed["prov_event_id"] = fixed["MOMI_id"] + "_E" + (fixed.groupby("MOMI_id").cumcount() + 1).astype(str).str.zfill(2)
fixed["check"] = fixed["event_text"].apply(check_event) # check again: this column should now be empty
fixedTurn each event into columns
Now we read each event with spaCy’s English model, which recognizes people (PERSON), organizations (ORG), places (GPE, LOC) and dates (DATE). The model learned English from news articles and does not know many art-world names, so we first teach it some names and patterns. Then each event becomes one row: the MoMI id, the event id, the event text, party 1, the method of transfer, party 2 (and party 3 and more if an event names more parties), the location and the date.
The code only fills in what the event says. In sold to Edith Wetmore, only the buyer is named, so Edith Wetmore goes in party 2 and party 1 stays empty: we do not guess who the seller was. The result is a first draft. Read it against the event text: when a name is missed or wrong, add it to the patterns or to NOT_PARTIES and run the cell again.
# Load the small English model: it finds people (PERSON), organizations (ORG), places (GPE, LOC) and dates (DATE)
try:
nlp = spacy.load("en_core_web_sm")
except OSError: # not installed yet: download it once
spacy.cli.download("en_core_web_sm")
nlp = spacy.load("en_core_web_sm")
# Teach it names and patterns it does not know (add your own when you find mistakes)
if "entity_ruler" in nlp.pipe_names:
nlp.remove_pipe("entity_ruler") # lets you run the cell again
ruler = nlp.add_pipe("entity_ruler", before="ner", config={"overwrite_ents": True})
ruler.add_patterns([
{"label": "PERSON", "pattern": "the artist"},
{"label": "PERSON", "pattern": "Gertrude Stein"},
{"label": "PERSON", "pattern": "Edith Wetmore"},
{"label": "PERSON", "pattern": "Mrs. Charles Sherwood Payson"},
{"label": "PERSON", "pattern": "Mr. and Mrs. Worcester"},
{"label": "PERSON", "pattern": "Alphonse Kann"},
{"label": "ORG", "pattern": "Bernheim-Jeune"},
{"label": "ORG", "pattern": "ERR"},
{"label": "ORG", "pattern": "Einsatzstab Reichsleiter Rosenberg"},
{"label": "ORG", "pattern": "Commission de récupération artistique"},
{"label": "GPE", "pattern": "Saint-Germain-en-Laye"},
{"label": "GPE", "pattern": "Carnoustie"},
# firms: "M. Knoedler & Co.", "Thomas Justice & Sons", "M. Knoedler and Company"
{"label": "ORG", "pattern": [{"IS_TITLE": True, "OP": "+"}, {"LOWER": {"IN": ["&", "and"]}},
{"LOWER": {"IN": ["co", "co.", "company", "sons"]}}]},
# galleries and museums: "Galerie Beyeler", "Art Institute of Chicago"
{"label": "ORG", "pattern": [{"TEXT": {"REGEX": "^[A-Z]"}, "OP": "*"},
{"TEXT": {"IN": ["Gallery", "Galleries", "Galerie", "Museum", "Institute"]}},
{"LOWER": "of", "OP": "?"}, {"IS_TITLE": True, "OP": "*"}]},
# auction houses: "Christie's", "Sotheby's"
{"label": "ORG", "pattern": [{"TEXT": {"IN": ["Christie", "Sotheby"]}}, {"TEXT": "'s"}]},
])
# Words the model takes for names, but that are not parties (add your own)
NOT_PARTIES = ["gift", "inc", "old master", "nazi"]
# Key words for each method of transfer; the first method that matches wins
METHODS = {
"restitution": ["restitute", "restitution", "return"],
"confiscation": ["confiscate", "seize", "loot"],
"exchange": ["trade", "exchange"],
"auction": ["auction", "lot", "christie", "sotheby"],
"bequest": ["bequeath", "bequest"],
"inheritance": ["descent", "inheritance", "inherit"],
"gift": ["gift", "give", "donate"],
"purchase": ["sell", "purchase", "buy", "francs", "dollars", "pounds"],
}
def find_method(doc):
words = {token.lemma_.lower() for token in doc} # dictionary form: "sold" -> "sell"
if "part of a lot" in doc.text:
words.discard("lot") # "part of a lot" is not an auction
for method, keywords in METHODS.items():
if words & set(keywords): # any key word in the event?
return method
return ""
# Remove what would be read as a party or a date by mistake
def prepare(text):
text = re.sub(r"\(\s*\d{4}\s*-\s*\d{4}\s*\)", "", text) # life dates, e.g. (1874-1946)
text = re.sub(r"\(stock[^)]*\)", "", text) # dealer notes, e.g. (stock no. 15701, as ...)
return text
QUALIFIERS = ["by", "until", "from", "before", "after", "ca", "circa"] # words that change a date's meaning
rows = []
for _, event in fixed.iterrows():
doc = nlp(prepare(event["event_text"]))
party_ents = [ent for ent in doc.ents if ent.label_ in ("PERSON", "ORG") and ent.text.lower() not in NOT_PARTIES]
parties = [ent.text for ent in party_ents]
locations = list(dict.fromkeys(ent.text for ent in doc.ents if ent.label_ in ("GPE", "LOC"))) # each place once
method = find_method(doc)
# "sold to X": X receives the work and the seller is not named, so party 1 stays empty
if method and party_ents and "to" in [t.lower_ for t in doc[:party_ents[0].start]]:
parties.insert(0, "")
dates = []
for ent in doc.ents:
if ent.label_ == "DATE" and re.search(r"\b1[5-9]\d\d\b|\b20\d\d\b", ent.text): # dates with a year
word_before = doc[ent.start - 1].lower_ if ent.start > 0 else ""
dates.append(f"{word_before} {ent.text}" if word_before in QUALIFIERS else ent.text)
row = {"MOMI_id": event["MOMI_id"], "prov_event_id": event["prov_event_id"], "event_text": event["event_text"]}
for n, party in enumerate(parties, start=1):
row[f"party_{n}"] = party # party_1, party_2, party_3 ...
row["method"] = method
row["location"] = "; ".join(locations)
row["date"] = "; ".join(dates)
rows.append(row)
structured = pd.DataFrame(rows).fillna("")
# Order the columns: MoMI id, event id, text, party 1, method, party 2, any further parties, location, date
party_columns = [c for c in structured.columns if c.startswith("party_")]
party_columns.sort(key=lambda c: int(c.split("_")[1]))
structured = structured[["MOMI_id", "prov_event_id", "event_text", party_columns[0], "method", *party_columns[1:], "location", "date"]]
structuredFind the parties: individuals and cultural entities
The last table lists the parties named in each artwork’s provenance, of two types: individuals (people) and cultural entities (dealers, galleries, museums, auction houses and other institutions). Every different name gets its own party_id, which does not depend on the artwork: the same name has the same id wherever it appears, so you can follow one dealer across many works.
Look at the names for Knoedler: M. Knoedler & Co., Knoedler, M. Knoedler and Company and Knoedler & Co. are one firm with four ids. Bringing them together under one id is the next step, reconciliation, in Data preprocessing.
# Two types of party: a person is an individual, an organization is a cultural entity
TYPES = {"PERSON": "individual", "ORG": "cultural entity"}
rows = []
for _, event in fixed.iterrows():
for ent in nlp(prepare(event["event_text"])).ents: # every name spaCy finds in the event
if ent.label_ in TYPES and ent.text.lower() not in NOT_PARTIES: # keep people and organizations only
rows.append({"MOMI_id": event["MOMI_id"], "party_name": ent.text, "party_type": TYPES[ent.label_]})
parties = pd.DataFrame(rows).drop_duplicates().reset_index(drop=True) # each name once per artwork
# Every different name gets its own id, the same in every artwork where it appears
ids = {name: f"PARTY_{n:03d}" for n, name in enumerate(parties["party_name"].unique(), start=1)}
parties["party_id"] = parties["party_name"].map(ids)
parties = parties[["MOMI_id", "party_id", "party_name", "party_type"]]
partiesSave and download the tables
This cell saves the three result tables as CSV files and puts all three in one Excel file, each table in its own sheet. Colab then downloads the four files to your computer, usually to your Downloads folder. Your browser may ask permission to download several files at once: click Allow. If a file does not arrive, open the folder icon in Colab’s left sidebar, right-click the file and choose Download. Colab deletes the files when the session ends, so download them before you close the notebook.
All tables start with MOMI_id, so they can be joined together and linked back to the artwork.
# The tables to save: a name for each file, and the table itself
tables = {
"events": fixed.drop(columns="check"), # the checked events, without the check column
"events_structured": structured, # one row per event: parties, method, location, date
"parties": parties, # individuals and cultural entities, with their ids
}
# Save each table as a CSV file; utf-8-sig keeps accents such as é readable in Excel
for name, table in tables.items():
table.to_csv(f"momi_{name}.csv", index=False, encoding="utf-8-sig")
# Save all tables in one Excel file, each table in its own sheet
with pd.ExcelWriter("momi_results.xlsx") as excel:
for name, table in tables.items():
table.to_excel(excel, sheet_name=name, index=False)
# Download the files from Colab to your computer, one by one
from google.colab import files
for name in tables:
files.download(f"momi_{name}.csv")
files.download("momi_results.xlsx")Data preprocessing
Agenda
Clean
Normalize
Harmonize
Reconcile
Slides
Datasets
Preprocessing datasets
The data we clean, normalize, harmonize and reconcile in this session. Download the files before you start the exercises.
Open the folderOpenRefine reconciliation
We reconcile the data in OpenRefine. To add a reconciliation service, open a column’s menu, choose Reconcile › Start reconciling…, click Add Standard Service… and paste one of the addresses below. Use the Copy button to copy an address.
Wikidata reconci.link (en)
https://wikidata.reconci.link/en/api
Getty Vocabularies Reconciliation Service
https://services.getty.edu/vocab/reconcile/
Sources
- OpenRefine
- CARE Principles for Indigenous Data Governance — Global Indigenous Data Alliance
- CIDOC-CRM, Version 7.3 — CIDOC CRM Special Interest Group
- Getty Vocabularies (AAT, ULAN, TGN) — Getty Research Institute
- Linked Art — Linked Art Community
- The FAIR Guiding Principles for Scientific Data Management and Stewardship — Wilkinson et al.
- The Virtual International Authority File (VIAF)
- Wikidata — A Free and Open Knowledge Base