Skip to main content

Purpose

Scenarios allow you create variations and versions of questions efficiently. For example, we could create a question “How much do you enjoy {{ scenario.activity }}?” and use scenarios to replace the parameter activity with running or reading or other activities. Similarly, we could create a question “What do you see in this image? {{ scenario.image }}” and use scenarios to replace the parameter image with different images.

How it works

Adding scenarios to a question–or to multiple questions at once in a survey–causes it to be administered multiple times, once for each scenario, with the parameter(s) replaced by the value(s) in the scenario. This allows us to administer different versions of a question together, either asynchronously (by default) or according to survey rules that we can specify (e.g., skip/stop logic), without having to create each version of a question manually.

Metadata

Scenarios are also a convenient way to keep track of metadata or other information relating to a survey that is important to an analysis of the results. For example, say we are using scenarios to parameterize question texts with pieces of {{ scenario.content }} from a dataset. In the scenarios that we create for the content parameter we could also include key/value pairs for metadata about the content, such as the {{ scenario.author }}, {{ scenario.publication_date }}, or {{ scenario.source }}. This will automatically include the data in the survey results but without requiring us to also parameterize the question texts those fields. This allows us to analyze the responses in the context of the metadata and avoid having to match up the data with the metadata post-survey. Please see more details on this feature in examples below.

Constructing a Scenario

To use a scenario, we start by creating a question that takes a parameter in double braces:
Next we create a dictionary for a value that will replace the parameter and store it in a Scenario object:
We can inspect the scenario and see that it consists of the key/value pair that we created:
This will return:

ScenarioList

If multiple values will be used with a question or survey, we can create a list of Scenario objects that will be passed to the question or survey together. For example, here we create a list of scenarios and inspect them:
Output:
Alternatively, we can create a ScenarioList object. A list of scenarios is used in the same way as a ScenarioList; the difference is that a ScenarioList is a class that can be used to create a list of scenarios from a variety of data sources, such as a CSV, dataframe, list, dictionary, a Wikipedia table or a PDF pages. These special methods are discussed below. For example, here we create a ScenarioList for the same list as above:
Output:

Special method for creating scenarios

We can use the general purpose from_source() method to create a ScenarioList from a variety of data source types. For example, the following code will create the same scenario list as above: Each source type has its own set of parameters that can be passed to it:
  • “csv”
  • “dataframe”
  • “delimited_file”
  • “dict”
  • “directory”
  • “dta”
  • “excel”
  • “google_doc”
  • “google_sheet”
  • “json”
  • “latex”
  • “list”
  • “list_of_tuples”
  • “pandas”
  • “parquet”
  • “pdf”
  • “png”
  • “pdf_to_image”
  • “text”
  • “tsv”
  • “sqlite”
  • “urls”
  • “wikipedia”
Here we create a scenario list from files in a directory:
Examples of these methods are provided below and in this notebook.

Using a scenario

We use a Scenario or ScenarioList by adding it to a question or survey of questions, either when we are constructing questions or when running them. If we add scenarios to a question when running a survey (using the by() method), the scenario contents replace the parameters in the question text at runtime, and are stored in a separate column of the results. If we add scenarios to a question when constructing a survey (using the loop() method), the scenario contents become part of the question text and there is no separate column of the results for the scenarios. The most common situation is to add a scenario to a question when running it. This is done by passing the Scenario or ScenarioList object to the by() method of a question or survey and then chaining the run() method. For example, here we call the by() method on the example question created above and pass a scenario list when we run it:
We can check the results to verify that the scenario has been used correctly:
This will print a table of the selected components of the results:

Looping

We use the loop() method to add scenarios to a question when constructing a survey. This method takes a ScenarioList and returns a list of new questions for each scenario that was passed. We can optionally include the scenario key in the question name as well as the question text. This allows us to control the question names when the new questions are created; otherwise a number is automatically added to the original question name in order to ensure uniqueness. For example:
We can inspect the questions to see that they have been created correctly:
This will return:
We can pass the questions to a survey and run it:
This will print a table of the response for each question. Note that “activity” is no longer in a separate scenario field; instead, there is a single column for each question that was constructed with the scenarios:
Note:The loop() method cannot be used with image or PDF scenarios, as these are not evaluated when the question is constructed. Instead, use the by() method to add these types of scenarios when running a survey (see image scenario examples below).

Multiple parameters

We can also create a Scenario for multiple parameters at once:
This will print a table of the selected components of the results: To learn more about constructing surveys, please see the Surveys module.

Scenarios for question options

In the above examples we created scenarios in the question_text. We can also create a Scenario for question_options, e.g., in a multiple choice, checkbox, linear scale or other question type that requires them. Note that we do not include the scenario. prefix when using scenarios for question options.
Output:

Scenario methods

There are a variety of methods for working with scenarios and scenario lists, including: concatenate, concatenate_to_list, concatenate_to_set, condense, drop, duplicate expand, filter, keep, mutate, order_by, rename, sample, shuffle, times, tranform, unpack_dict These methods can be used to manipulate scenarios and scenario lists in various ways, such as sampling a subset of scenarios, shuffling the order of scenarios, concatenating scenarios together, filtering scenarios based on certain criteria, and more. Examples of some of these methods are provided below.

Combining Scenarios

We can combine multiple scenarios into a single Scenario object:
This will return: We can also combine ScenarioList objects:
This will return: We can create a cross product of ScenarioList objects (combine the scenarios in each list with each other):
This will return:

Concatenating scenarios

There are several ScenarioList methods for concatenating scenarios. The method concatenate() can be used to concatenate specified fields into a single string field; the default separator is a semicolon:
This will return: We can specify a different separator:
This will return: The method concatenate_to_list() can be used to concatenate specified fields into a single list field:
This will return: The method concatenate_to_set() can be used to concatenate specified fields into a single set field:
This will return: The method collapse() can be used to collapse a scenario list by grouping on all fields except a specified field:
This will return: The method condense() can be used to combine all scenarios in a ScenarioList into a single Scenario object:
This will return: The condensed scenario can then be used in EDSL questions with dot notation:
You can also use custom prefixes and control whether to include indices:
This will return:

Creating scenarios from a dataset

There are a variety of methods for creating and working with scenarios generated from datasets and different data types.

Turning results into scenarios

The method to_scenario_list() can be used to turn the results of a survey into a list of scenarios. Example usage: Say we have some results from a survey where we asked agents to choose a random number between 1 and 1000:
Our results are: We can use the to_scenario_list() method turn components of the results into a list of scenarios to use in a new survey:
We can inspect the scenarios to see that they have been created correctly:

PDFs as textual scenarios

The ScenarioList method from_source(“pdf”, “path/to/pdf”) is a convenient way to extract information from large files. It allows you to read in a PDF and automatically create a list of textual scenarios for the individual pages of the file. Each scenario has the following keys which can be used as parameters in a question or stored as metadata, and renamed as desired: filename, page, text:
If you prefer to create a single Scenario for the entire PDF file, you can use the FileStore module to pass the file to a Scenario in the usual way (e.g., this method is identical for PNG image files):
To use this method with either object, we start by adding a placeholder {{ scenario.text }} to a question text where the text of a PDF or PDF page will be inserted. When the question or survey is run with the PDF scenario or scenario list, the text of the PDF or individual pages will be inserted into the question text at the placeholder. For example, this code can be used to insert the text of each page of a PDF in a survey of question:
Examples of this method can be viewed in a demo notebook.

Image scenarios

A Scenario can be generated from an image by passing the filepath as the value (the same as a PDF, as shown above). This is done by using the FileStore module to store the image and then passing the FileStore object to a Scenario. Example usage:
We can add the key to questions as we do scenarios from other data sources:
Output using the Expected Parrot logo: See a demo notebook using of this method in the documentation page.
Note:You must use a vision model in order to run questions with images. We recommend testing whether a model can reliably identify your images before running a survey with them. You can also use the models page to check available models’ performance with test questions, including images.

Creating a scenario list from a list

Example usage:
This will return:

Creating a scenario list from a dictionary

Example usage:
This will return:

Creating a scenario list from a Wikipedia table

Example usage:
This will return a list of scenarios for the first table on the Wikipedia page: The parameters let us know the keys that can be used in the question text or stored as metadata. (They can be edited as needed - e.g., using the rename method discussed above.)
This will return:
The scenarios can be used to ask questions about the data in the table:
Output:

Creating a scenario list from a CSV

The ScenarioList method from_source(“csv”, “<filepath>.csv”) creates a list of scenarios from a CSV file. The method reads the CSV file and creates a scenario for each row in the file, with the keys as the column names and the values as the row values. For example, say we have a CSV file containing the following data:
We can create a list of scenarios from the CSV file:
This will return a scenario for each row: If the scenario keys are not valid Python identifiers, we can use the give_valid_names() method to convert them to valid identifiers. For example, our CSV file might contain a header row that is question texts:
We can create a list of scenarios from the CSV file:
This will return scenarios with non-Pythonic identifiers: We can then use the give_valid_names() method to convert the keys to valid identifiers:
This will return scenarios with valid identifiers (removing stop words and using underscores):

Methods for un/pivoting and grouping scenarios

There are a variety of methods for modifying scenarios and scenario lists.

Unpivoting a scenario list

The ScenarioList method unpivot() can be used to unpivot a scenario list based on one or more specified identifiers. It takes a list of id_vars which are the names of the key/value pairs to keep in each new scenario, and a list of value_vars which are the names of the key/value pairs to unpivot. For example, say we have a scenario list for the above CSV file:
We can call the unpivot the scenario list:
This will return a list of scenarios with the source, date, and message key/value pairs unpivoted:

Pivoting a scenario list

We can call the pivot() method to reverse the unpivot operation:
This will return a list of scenarios with the source, date, and message key/value pairs pivoted back to their original form:

Grouping scenarios

The group_by() method can be used to group scenarios by one or more specified keys and apply a function to the values of the specified variables. Example usage:
This will return a list of scenarios with the a and b key/value pairs grouped by the group key and the avg_a and sum_b key/value pairs calculated by the avg_sum function:

Data labeling tasks

Scenarios are particularly useful for conducting data labeling or data coding tasks, where the task can be designed as a survey of questions about each piece of data in a dataset. For example, say we have a dataset of text messages that we want to sort by topic. We can perform this task by using a language model to answer questions such as “What is the primary topic of this message: {{ scenario.message }}?” or “Does this message mention a safety issue? {{ scenario.message }}”, where each text message is inserted in the message placeholder of the question text. Here we use scenarios to conduct the task:
We can then analyze the results to see how the agent answered the questions for each scenario:
This will print a table of the scenarios and the answers to the questions for each scenario:

Adding metadata

If we have metadata about the messages that we want to keep track of, we can add it to the scenarios as well. This will create additional columns for the metadata in the results dataset, but without the need to include it in our question texts. Here we modify the above example to use a dataset of messages with metadata. Note that the question texts are unchanged:
We can see how the agent answered the questions for each scenario, together with the metadata that was not included in the question text: To learn more about accessing, analyzing and visualizing survey results, please see the Results section.

Slicing/chunking content into scenarios

We can use the Scenario method chunk() to slice a text scenario into a ScenarioList based on num_words or num_lines. Example usage:
This will return:

Using f-strings with scenarios

It is possible to use scenarios and f-strings together in a question. An f-string must be evaluated when a question is constructed, whereas a scenario is either evaluated when a question is run (using the by method) or when a question is constructed (using the loop method). For example, here we use an f-string to create different versions of a question that also takes a parameter {{ scenario.activity }}, together with a list of scenarios to replace the parameter when the question is run. We optionally include the f-string in the question name in addition to the question text in order to control the unique identifiers for the questions, which are needed in order to pass the questions that are created to a Survey. (If you do not include the f-string in the question name, a number is automatically appended to each question name to ensure uniqueness.) Then we use the show_prompts() method to examine the user prompts that are created when the scenarios are added to the questions:
The show_prompts method will return the questions created with the f-string with the scenarios added. (Note that the system prompts are blank because we have not created any agents.) To learn more about user and system prompts, please see the Prompts section.

Special methods

Special methods are available for generating or modifying scenarios using web searches: The from_prompt method allows you to create scenarios from a prompt, which can be useful for generating scenarios based on user input or other dynamic sources:
The from_search_terms method allows you to create scenarios from a list of search terms, which can be useful for generating scenarios based on search queries or other dynamic sources:
The method augment_with_wikipedia allows you to augment scenarios with information from Wikipedia, which can be useful for enriching scenarios with additional context or data:

Scenario class

class edsl.scenarios.Scenario(data: Dict[str, Any] | Mapping[str, Any] | None = None, name: str | None = None) [source]

Bases: Base, UserDict A dictionary-like object that stores key-value pairs for parameterizing questions. A Scenario inherits from both the EDSL Base class and Python’s UserDict, allowing it to function as a dictionary while providing additional functionality. Scenarios are used to parameterize questions by providing variable data that can be referenced within question templates using Jinja syntax. Scenarios can be created directly with dictionary data or constructed from various sources using class methods (from_file, from_url, from_pdf, etc.). They support operations like addition (combining scenarios) and multiplication (creating cross products with other scenarios or scenario lists).

Attributes:

data (dict): The underlying dictionary data. name (str, optional): A name for the scenario.

Examples:

Create a simple scenario: >>> s = Scenario({“product”: “coffee”, “price”: 4.99}) Combine scenarios: >>> s1 = Scenario({“product”: “coffee”}) >>> s2 = Scenario({“price”: 4.99}) >>> s3 = s1 + s2 >>> s3 Scenario({‘product’: ‘coffee’, ‘price’: 4.99}) Create a scenario from a file: >>> import tempfile >>> with tempfile.NamedTemporaryFile(mode=’w’, suffix=’.txt’, delete=False) as f: … _ = f.write(“Hello World”) … data_path = f.name >>> s = Scenario.from_file(data_path, “document”) >>> import os >>> os.unlink(data_path) # Clean up temp file

**init(data: Dict[str, Any] | Mapping[str, Any] | None = None, name: str | None = None) [source]

Initialize a new Scenario.
Args:
data: A dictionary of key-value pairs for parameterizing questions. Any dictionary-like object that can be converted to a dict is accepted. name: An optional name for the scenario to aid in identification.
Raises:
ScenarioError: If the data cannot be converted to a dictionary.
Examples:

**chunk(field: str, num_words: int | None = None, num_lines: int | None = None, include_original: bool = False, hash_original: bool = False) → ScenarioList [source]

Splits a text field into chunks of a specified size, creating a ScenarioList. This method takes a field containing text and divides it into smaller chunks based on either word count or line count. It’s particularly useful for processing large text documents in manageable pieces, such as for summarization, analysis, or when working with models that have token limits.
Args:
field: The key name of the field in the Scenario to split. num_words: The number of words to include in each chunk. Mutually exclusive
num_lines: The number of lines to include in each chunk. Mutually exclusive
include_original: If True, includes the original complete text in each chunk
original text instead of the full text.
Returns:
A ScenarioList containing multiple Scenarios, each with a chunk of the original text. Each Scenario includes the chunk text, chunk index, character count, and word count.
Raises:
ValueError: If neither num_words nor num_lines is specified, or if both are. KeyError: If the specified field doesn’t exist in the Scenario.
Examples:
Notes:
  • Either num_words or num_lines must be specified, but not both
  • Each chunk is assigned a sequential index in the ‘text_chunk’ field
  • Character and word counts for each chunk are included
  • When include_original is True, the original text is preserved in each chunk
  • The hash_original option is useful to save space while maintaining traceability

chunk_text(field: str, chunk_size_field: str, unit: str = ‘word’, include_original: bool = False, hash_original: bool = False) → ScenarioList [source ]

Chunks a text field into smaller chunks of a specified size, creating a ScenarioList. This method takes a field containing text and divides it into smaller chunks based on either word count or line count. It’s particularly useful for processing large text documents in manageable pieces, such as for summarization, analysis, or when working with models that have token limits.

code() → List[str] [source]

Generate Python code to recreate this scenario.
Returns:
A list of strings representing Python code lines that can be executed to recreate this scenario.
Examples:

drop(**args: str | Iterable[str]*) → Scenario [source ]

Drop a subset of keys from a scenario. This method delegates to ScenarioSelector for the actual dropping logic. It supports both individual string arguments and collection arguments for backward compatibility.
Args:
*args: Either a single collection of keys (for backward compatibility) or individual string arguments for keys to drop.
Returns:
A new Scenario containing all keys except the dropped ones.
Raises:
ValueError: If no arguments are provided.
Examples:

classmethod example(randomize: bool = False) → Scenario [source ]

Returns an example Scenario instance.
Args:
randomize: If True, adds a random string to the value of the example key to ensure uniqueness.
Returns:
A Scenario instance with example data suitable for testing or demonstration.
Examples:

firecrawl = <edsl.scenarios.firecrawl_scenario.FirecrawlRequest object> [source]

classmethod from_dict(d: Dict[str, Any]) → Scenario [source ]

Creates a Scenario from a dictionary, with special handling for FileStore objects. This method creates a Scenario using the provided dictionary. It has special handling for dictionary values that represent serialized FileStore objects, which it will deserialize back into proper FileStore instances.
Args:
d: A dictionary to convert to a Scenario.
Returns:
A new Scenario containing the provided dictionary data.
Examples:
Notes:
  • Any dictionary values that match the FileStore format will be converted to FileStore objects
  • The method detects FileStore objects by looking for “base64_string” and “path” keys
  • EDSL version information is automatically removed by the @remove_edsl_version decorator
  • This method is commonly used when deserializing scenarios from JSON or other formats

classmethod from_docx(docx_path: str) → Scenario [source ]

Creates a Scenario containing text extracted from a Microsoft Word document. This method extracts text and structure from a DOCX file and creates a Scenario containing this information. It uses the DocxScenario class to handle the extraction process and maintain document structure where possible.
Args:
docx_path: Path to the DOCX file to extract content from.
Returns:
A Scenario containing the file path and extracted text from the DOCX file.
Raises:
FileNotFoundError: If the specified DOCX file does not exist. ImportError: If the python-docx library is not installed.
Examples:
Notes:
  • The returned Scenario typically contains the file path and extracted text
  • The extraction process attempts to maintain document structure
  • Requires the python-docx library to be installed

classmethod from_file(file_path: str, field_name: str) → Scenario [source ]

Creates a Scenario containing a FileStore object from a file. This method creates a Scenario with a single key-value pair where the value is a FileStore object that encapsulates the specified file. The FileStore handles appropriate file loading, encoding, and extraction based on the file type.
Args:
file_path: Path to the file to be incorporated into the Scenario. field_name: Key name to use for storing the FileStore in the Scenario.
Returns:
A Scenario containing a FileStore object linked to the specified file.
Raises:
FileNotFoundError: If the specified file does not exist.
Examples:
Notes:
  • The FileStore object handles various file formats differently
  • FileStore provides methods to access file content, extract text, and manage file operations appropriate to the file type

classmethod from_html(url: str, field_name: str | None = None) → Scenario [source ]

Creates a Scenario containing both HTML content and extracted text from a URL. This method fetches HTML content from a URL, extracts readable text from it, and creates a Scenario containing the original URL, the raw HTML, and the extracted text. Unlike from_url, this method preserves the raw HTML content.
Args:
url: URL to fetch HTML content from. field_name: Key name to use for the extracted text in the Scenario. If not provided, defaults to “text”.
Returns:
A Scenario containing the URL, raw HTML, and extracted text.
Raises:
requests.exceptions.RequestException: If the URL cannot be accessed.
Examples:
Create a scenario from HTML content (requires network access): s = Scenario.from_html(”https://example.com”) # Returns a Scenario with “url”, “html”, and “text” fields s = Scenario.from_html(”https://example.com”, field_name=”content”) # Returns a Scenario with “url”, “html”, and “content” fields
Notes:
  • Uses BeautifulSoup for HTML parsing when available
  • Stores both the raw HTML and the extracted text
  • Provides a more comprehensive representation than from_url
  • Useful when the HTML structure or specific elements are needed

classmethod from_image(image_path: str, image_name: str | None = None) → Scenario [source ]

Creates a Scenario containing an image file as a FileStore object. This method creates a Scenario with a single key-value pair where the value is a FileStore object that encapsulates the specified image file. The image is stored as a base64-encoded string, allowing it to be easily serialized and transmitted.
Args:
image_path: Path to the image file to be incorporated into the Scenario. image_name: Key name to use for storing the FileStore in the Scenario. If not provided, uses the filename without extension.
Returns:
A Scenario containing a FileStore object with the image data.
Raises:
FileNotFoundError: If the specified image file does not exist.
Examples:
import os

Assuming an image file exists

if os.path.exists(“image.jpg”): … s = Scenario.from_image(“image.jpg”) … s_named = Scenario.from_image(“image.jpg”, “picture”)
Notes:
  • The resulting FileStore can be displayed in notebooks or used in questions
  • Supported image formats include JPG, PNG, GIF, etc.
  • The image is stored as a base64-encoded string for portability

classmethod from_pdf(pdf_path: str) → Scenario [source ]

Creates a Scenario containing text extracted from a PDF file. This method extracts text and metadata from a PDF file and creates a Scenario containing this information. It uses the PdfExtractor class which provides access to text content, metadata, and structure from PDF files.
Args:
pdf_path: Path to the PDF file to extract content from.
Returns:
A Scenario containing extracted text and metadata from the PDF.
Raises:
FileNotFoundError: If the specified PDF file does not exist. ImportError: If the required PDF extraction libraries are not installed.
Examples:
Notes:
  • The returned Scenario contains various keys with PDF content and metadata
  • PDF extraction requires the PyMuPDF library
  • The extraction process parses the PDF to maintain structure where possible

classmethod from_pdf_to_image(pdf_path: str, image_format: str = ‘jpeg’) → Scenario [source ]

Converts each page of a PDF into an image and creates a Scenario containing them. This method takes a PDF file, converts each page to an image in the specified format, and creates a Scenario containing the original file path and FileStore objects for each page image. This is particularly useful for visualizing PDF content or for image-based processing of PDF documents.
Args:
pdf_path: Path to the PDF file to convert to images. image_format: Format of the output images (default is ‘jpeg’). Other formats include ‘png’, ‘tiff’, etc.
Returns:
A Scenario containing the original PDF file path and FileStore objects for each page image, with keys like “page_0”, “page_1”, etc.
Raises:
FileNotFoundError: If the specified PDF file does not exist. ImportError: If pdf2image is not installed.
Examples:
Notes:
  • Requires the pdf2image library which depends on poppler
  • Creates a separate image for each page of the PDF
  • Images are stored in FileStore objects for easy display and handling
  • Images are created in a temporary directory which is automatically cleaned up

classmethod from_url(url: str, field_name: str | None = ‘text’, testing: bool = False) → Scenario [source ]

Creates a Scenario from the content of a URL. This method fetches content from a web URL and creates a Scenario containing the URL and the extracted text. When available, BeautifulSoup is used for better HTML parsing and text extraction, otherwise a basic requests approach is used.
Args:
url: The URL to fetch content from. field_name: The key name to use for storing the extracted text in the Scenario. Defaults to “text”. testing: If True, uses a simplified requests method instead of BeautifulSoup. This is primarily for testing purposes.
Returns:
A Scenario containing the URL and extracted text.
Raises:
requests.exceptions.RequestException: If the URL cannot be accessed.
Examples:
Create a scenario from a URL (requires network access): s = Scenario.from_url(”https://example.com”, testing=True) # Returns a Scenario with “url” and “text” fields s = Scenario.from_url(”https://example.com”, field_name=”content”, testing=True) # Returns a Scenario with “url”, “html”, and “content” fields
Notes:
  • The method attempts to use BeautifulSoup and fake_useragent for better HTML parsing and to mimic a real browser.
  • If these packages are not available, it falls back to basic requests.
  • When using BeautifulSoup, it extracts text from paragraph and heading tags.

get_filestore_info() → Dict[str, Any] [source]

Returns information about FileStore objects present in this Scenario. This method is useful for determining how many signed URLs need to be generated and what file extensions/types are present before calling save_to_gcs_bucket().
Returns:
dict: Information about FileStore objects containing:
  • total_count: Total number of FileStore objects
  • filestore_keys: List of scenario keys that contain FileStore objects
  • file_extensions: Dictionary mapping keys to file extensions
  • file_types: Dictionary mapping keys to MIME types
  • is_filestore_scenario: Boolean indicating if this Scenario was created from a FileStore
  • summary: Human-readable summary of files

property has_jinja_braces*: bool* [source]

Return whether the scenario has jinja braces. This matters for rendering.

keep(**args: str | Iterable[str]*) → Scenario [source ]

Keep a subset of keys from a scenario (alias for select). This method delegates to ScenarioSelector for the actual selection logic. It is functionally identical to select() but provides more intuitive naming.
Args:
*args: Either a single collection of keys (for backward compatibility) or individual string arguments for keys to keep.
Returns:
A new Scenario containing only the kept keys and their values.
Raises:
KeyError: If any of the specified keys don’t exist in the scenario. ValueError: If no arguments are provided.
Examples:
Using a list (backward compatible): >>> s = Scenario({“food”: “wood chips”, “drink”: “water”}) >>> s.keep([“food”]) Scenario({‘food’: ‘wood chips’}) Using individual string arguments: >>> s = Scenario({“food”: “wood chips”, “drink”: “water”, “dessert”: “cookies”}) >>> s.keep(“food”, “drink”) Scenario({‘food’: ‘wood chips’, ‘drink’: ‘water’})

new_column_names(new_names: List[str]) → Scenario [source ]

Rename all keys of a scenario using a list of new names.
Args:
new_names: A list of new key names. Must have the same length as the number of keys in the scenario.
Returns:
A new Scenario with keys renamed according to the provided list.
Raises:
ValueError: If the length of new_names doesn’t match the number of keys.
Examples:

offload(inplace: bool = False) → Scenario [source ]

Offload base64-encoded content from the scenario by replacing ‘base64_string’ fields with ‘offloaded’. This reduces memory usage. This method delegates to ScenarioOffloader for the actual offloading logic. It handles three types of base64 content: 1. Direct base64_string in the scenario (from FileStore.to_dict()) 2. FileStore objects containing base64 content 3. Dictionary values containing base64_string fields
Args:
inplace: If True, modify the current scenario. If False, return a new one.
Returns:
The modified scenario (either self or a new instance).
Examples:
Basic offloading: >>> s = Scenario({“base64_string”: “SGVsbG8gV29ybGQ=”, “name”: “test”}) >>> offloaded = s.offload() >>> offloaded[“base64_string”] ‘offloaded’ >>> offloaded[“name”] ‘test’ In-place offloading: >>> s = Scenario({“base64_string”: “SGVsbG8gV29ybGQ=”, “name”: “test”}) >>> result = s.offload(inplace=True) >>> result is s True >>> s[“base64_string”] ‘offloaded’

open_url(position: int = 0) → None [source]

Open a URL field from the scenario in the default web browser.
Args:
position: The index of the URL to open (0-based). Defaults to 0 for the first URL.
Raises:
ValueError: If no URL fields are found in the scenario, or if the position is out of range.
Examples:

rename(old_name_or_replacement_dict: str | Dict[str, str], new_name: str | None = None) → Scenario [source ]

Rename the keys of a scenario.
Args:
old_name_or_replacement_dict: Either a dictionary mapping old keys to new keys, or a string representing the old key name. new_name: The new name for the key. Required if old_name_or_replacement_dict is a string, ignored if it’s a dictionary.
Returns:
A new Scenario with renamed keys.
Raises:
TypeError: If old_name_or_replacement_dict is a string but new_name is None.
Examples:
Using a dictionary: >>> s = Scenario({“food”: “wood chips”}) >>> s.rename({“food”: “food_preference”}) Scenario({‘food_preference’: ‘wood chips’}) Using individual arguments: >>> s = Scenario({“food”: “wood chips”}) >>> s.rename(“food”, “snack”) Scenario({‘snack’: ‘wood chips’})

replicate(n: int) → ScenarioList [source ]

Replicate a scenario n times to return a ScenarioList.
Args:
n: The number of times to replicate the scenario. Must be non-negative.
Returns:
A ScenarioList containing n copies of this scenario.
Raises:
ValueError: If n is negative.
Examples:

save_to_gcs_bucket(signed_url_or_dict: str | Dict[str, str]) → Dict[str, Any] [source]

Saves FileStore objects contained within this Scenario to a Google Cloud Storage bucket. This method finds all FileStore objects in the Scenario and uploads them to GCS using the provided signed URL(s). If the Scenario itself was created from a FileStore (has base64_string as a top-level key), it uploads that content directly.
Args:
signed_url_or_dict: Either:
  • str: Single signed URL (for single FileStore or Scenario from FileStore)
  • dict: Mapping of scenario keys to signed URLs for multiple FileStore objects e.g., {“video”: “signed_url_1”, “image”: “signed_url_2”}
Returns:
dict: Summary of upload operations performed
Raises:
ValueError: If no uploadable content found or content is offloaded requests.RequestException: If any upload fails

select(**args: str | Iterable[str]*) → Scenario [source ]

Select a subset of keys from a scenario. This method delegates to ScenarioSelector for the actual selection logic. It supports both individual string arguments and collection arguments for backward compatibility.
Args:
*args: Either a single collection of keys (for backward compatibility) or individual string arguments for keys to select.
Returns:
A new Scenario containing only the selected keys and their values.
Raises:
KeyError: If any of the specified keys don’t exist in the scenario. ValueError: If no arguments are provided.
Examples:
Using a list (backward compatible): >>> s = Scenario({“food”: “wood chips”, “drink”: “water”}) >>> s.select([“food”]) Scenario({‘food’: ‘wood chips’}) Using individual string arguments: >>> s = Scenario({“food”: “wood chips”, “drink”: “water”, “dessert”: “cookies”}) >>> s.select(“food”, “drink”) Scenario({‘food’: ‘wood chips’, ‘drink’: ‘water’}) Single string argument: >>> s.select(“food”) Scenario({‘food’: ‘wood chips’})

table(tablefmt: str = ‘grid’) → str [source]

Display a scenario as a formatted table.
Args:
tablefmt: The table format to use. Common options include “grid”, “simple”, “pipe”, “orgtbl”, “rst”, “mediawiki”, “html”, “latex”.
Returns:
A string representation of the scenario formatted as a table.
Examples:

to(question_or_survey: ‘Question’ | ‘Survey’) → Jobs [source]

Send the scenario to a question or survey for execution.
Args:
question_or_survey: A Question or Survey object to parameterize with this scenario.
Returns:
A Jobs object that can be run to execute the question or survey with this scenario.
Examples:

to_dataset() → Dataset [source]

Convert a scenario to a dataset.

to_dict(add_edsl_version: bool = True, offload_base64: bool = False) → Dict[str, Any] [source]

Convert a scenario to a dictionary.
Args:
add_edsl_version: If True, adds the EDSL version to the returned dictionary. offload_base64: If True, replaces any base64_string fields with ‘offloaded’ to reduce memory usage. Example:

ScenarioList class

class edsl.scenarios.ScenarioList(data: list | None = None, codebook: dict[str, str] | None = None, data_class: type | None = <class ‘list’>) [source]

Bases: MutableSequence, Base [source], ScenarioListOperationsMixin A collection of Scenario objects with advanced operations for manipulation and analysis. ScenarioList provides specialized functionality for working with collections of Scenario objects. It inherits from MutableSequence to provide standard list operations, from Base to integrate with EDSL’s object model, and from ScenarioListOperationsMixin to provide powerful data manipulation capabilities. Attributes: data (list): The underlying list containing Scenario objects. codebook (dict): Optional metadata describing the fields in the scenarios.

init(data: list | None = None, codebook: dict[str, str] | None = None, data_class: type | None = <class ‘list’>) [source]

Initialize a new ScenarioList with optional data and codebook.

add_list(name: str, values: List[Any]) → ScenarioList [source ]

Add a list of values to a ScenarioList. Example:

add_value(name: str, value: Any) → ScenarioList [source ]

Add a value to all scenarios in a ScenarioList. Example:

apply(func: Callable, field: str, new_name: str | None, replace: bool = False) → ScenarioList [source ]

Apply a function to a field and return a new ScenarioList.

at(index: int) → Scenario [source ]

Get the scenario at the specified index position. >>> sl = ScenarioList.from_list(“a”, [1, 2, 3]) >>> sl.at(0) Scenario({‘a’: 1}) >>> sl.at(-1) Scenario({‘a’: 3})

augment_with_wikipedia(search_key: str, content_only: bool = True, key_name: str = ‘wikipedia_content’) → ScenarioList [source ]

Augment the ScenarioList with Wikipedia content.

chart() [source]

Create a chart from the results.

chunk(field, num_words: int | None = None, num_lines: int | None = None, include_original=False, hash_original=False) → ScenarioList [source ]

Chunk the scenarios based on a field.
Examples:

clipboard_data() → str [source]

Return TSV representation of this object for clipboard operations. This method is called by the clipboard() method in the base class to provide a custom format for copying objects to the system clipboard. Returns: str: Tab-separated values representation of the object

code() → str [source]

Create the Python code representation of a survey.

collapse(field: str, separator: str | None = None, prefix: str = ”, postfix: str = ”, add_count: bool = False) → ScenarioList [source ]

Collapse by grouping on all fields except the specified one. Delegates to ScenarioListTransformer.collapse.

concatenate(fields: List[str], separator: str = ’;’, prefix: str = ”, postfix: str = ”, new_field_name: str | None = None) → ScenarioList [source ]

Concatenate specified fields into a single string field. Delegates to ScenarioListTransformer.concatenate for implementation.

concatenate_to_list(fields: List[str], prefix: str = ”, postfix: str = ”, new_field_name: str | None = None) → ScenarioList [source ]

Concatenate specified fields into a single list field. Delegates to ScenarioListTransformer.concatenate_to_list for implementation.

concatenate_to_set(fields: List[str], prefix: str = ”, postfix: str = ”, new_field_name: str | None = None) → ScenarioList [source ]

Concatenate specified fields into a single set field. Delegates to ScenarioListTransformer.concatenate_to_set for implementation.

copy() [source]

Create a copy of this ScenarioList. Returns: A new ScenarioList with copies of the same scenarios

create_comparisons(bidirectional: bool = False, num_options: int = 2, option_prefix: str = ‘option_’, use_alphabet: bool = False) → ScenarioList [source ]

Create a new ScenarioList with comparisons between scenarios. Delegates to ScenarioListTransformer.create_comparisons.

create_conjoint_comparisons(attribute_field: str = ‘attribute’, levels_field: str = ‘levels’, count: int = 1, random_seed: int | None = None) → ScenarioList [source ])

Generate random product profiles for conjoint analysis from attribute definitions. This method uses the current ScenarioList (which should contain attribute definitions) to create random product profiles by sampling from the attribute levels. Each scenario in the current list should represent one attribute with its possible levels.
Args:
attribute_field: Field name containing the attribute names (default: ‘attribute’) levels_field: Field name containing the list of levels (default: ‘levels’) count: Number of product profiles to generate (default: 1) random_seed: Optional seed for reproducible random sampling
Returns:
ScenarioList containing randomly generated product profiles
Examples:
Raises:
ScenarioError: If the current ScenarioList doesn’t have the required fields ValueError: If count is not positive

create_empty_scenario_list(n: int) → ScenarioList [source ]

Create an empty ScenarioList with n scenarios.
Args:
n: The number of empty scenarios to create
Examples:

drop(*fields: str) → ScenarioList [source ]

Drop fields from the scenarios. Example:

duplicate() → ScenarioList [source ]

Return a copy of the ScenarioList using streaming to avoid loading everything into memory.

equals(other: Any) → bool [source]

Memory-efficient comparison of two ScenarioLists.

classmethod example(randomize: bool = False) → ScenarioList [source ]

Return an example ScenarioList instance. Params randomize: If True, use Scenario’s randomize method to randomize the values.

expand(expand_field: str, number_field: bool = False) → ScenarioList [source ]

Expand the ScenarioList by a field. Parameters:
  • expand_field – The field to expand.
  • number_field – Whether to add a field with the index of the value
Example:

fillna(value: Any = ”, inplace: bool = False) → ScenarioList [source ]

Fill None/NaN values in all scenarios with a specified value. This method is equivalent to pandas’ df.fillna() functionality, allowing you to replace None, NaN, or other null-like values across all scenarios in the list.
Args:
value: The value to use for filling None/NaN values. Defaults to empty string “”. inplace: If True, modify the original ScenarioList. If False (default), return a new ScenarioList with filled values.
Returns:
ScenarioList: A new ScenarioList with filled values, or self if inplace=True
Examples:

filter(expression: str) → ScenarioList [source ]

Filter a list of scenarios based on an expression. Delegates to ScenarioListTransformer.filter.

firecrawl = <edsl.scenarios.firecrawl_scenario.FirecrawlRequest object> [source]

flatten(field: str, keep_original: bool = False) → Dataset [source]

Expand a field containing dictionaries into separate fields. This method takes a field that contains a list of dictionaries and expands it into multiple fields, one for each key in the dictionaries. This is useful when working with nested data structures or results from extraction operations.
Parameters:
field: The field containing dictionaries to flatten keep_original: Whether to retain the original field in the result
Returns:
A new Dataset with the dictionary keys expanded into separate fields
Notes:
  • Each key in the dictionaries becomes a new field with name pattern “.
  • All dictionaries in the field must have compatible structures
  • If a dictionary is missing a key, the corresponding value will be None
  • Non-dictionary values in the field will cause a warning
Examples:

for_n(target: ‘Question’ | ‘Survey’ | ‘Job’, iterations: int) → Jobs [source]

Execute a target multiple times, feeding each iteration’s output into the next.

Parameters

targetQuestion | Survey | Job The object to be executed on each round. A fresh duplicate() of target is taken for every iteration so that state is not shared between runs. iterationsint How many times to run target.

Returns

Jobs A Jobs instance containing the results of the final iteration.

classmethod from_csv(source: str | ‘ParseResult’, has_header: bool = True, encoding: str = ‘utf-8’, **kwargs) → ScenarioList [source ]

Create a ScenarioList from a CSV file or URL.
Args:
source: Path to a local file or URL to a remote file. has_header: Whether the file has a header row (default is True). encoding: The file encoding to use (default is ‘utf-8’). **kwargs: Additional parameters for csv reader.
Returns:
ScenarioList: An instance of the ScenarioList class.

classmethod from_delimited_file(source: str | ‘ParseResult’, delimiter: str = ’,’, encoding: str = ‘utf-8’, **kwargs) → ScenarioList [source ]

Create a ScenarioList from a delimited file (CSV/TSV) or URL.
Args:
source: Path to a local file or URL to a remote file. delimiter: The delimiter character used in the file (default is ‘,’). encoding: The file encoding to use (default is ‘utf-8’). **kwargs: Additional parameters for csv reader.
Returns:
ScenarioList: An instance of the ScenarioList class.

classmethod from_dict(data: dict) → ScenarioList [source ]

Create a ScenarioList from a dictionary.

classmethod from_directory(path: str | None = None, recursive: bool = False, key_name: str = ‘content’) → ScenarioList [source ]

Create a ScenarioList of Scenario objects from files in a directory. This method scans a directory and creates a Scenario object for each file found, where each Scenario contains a FileStore object under the specified key. Optionally filters files based on a wildcard pattern. If no path is provided, the current working directory is used.
Args:
path: The directory path to scan, optionally including a wildcard pattern. If None, uses the current working directory. Examples: - “/path/to/directory” - scans all files in the directory - “/path/to/directory/.py” - scans only Python files in the directory - “.txt” - scans only text files in the current working directory recursive: Whether to scan subdirectories recursively. Defaults to False. key_name: The key to use for the FileStore object in each Scenario. Defaults to “content”.
Returns:
A ScenarioList containing Scenario objects for all matching files, where each Scenario has a FileStore object under the specified key.
Raises:
FileNotFoundError: If the specified directory does not exist.
Examples:

classmethod from_list(field_name: str, values: list, use_indexes: bool = False) → ScenarioList [source]

Create a ScenarioList from a list of values with a specified field name.

classmethod from_nested_dict(data: dict) → ScenarioList [source]

Create a ScenarioList from a nested dictionary.

classmethod from_prompt(description: str, name: str | None = ‘item’, target_number: int = 10, verbose=False)[source]

classmethod from_search_terms(search_terms: List[str]) → ScenarioList [source]

Create a ScenarioList from a list of search terms, using Wikipedia. Args: search_terms: A list of search terms.

classmethod from_source(source_type: str, *args, **kwargs) → ScenarioList [source]

Create a ScenarioList from a specified source type. This method serves as the main entry point for creating ScenarioList objects, providing a unified interface for various data sources. Args: source_type: The type of source to create a ScenarioList from. Valid values include: ‘urls’, ‘directory’, ‘csv’, ‘tsv’, ‘excel’, ‘pdf’, ‘pdf_to_image’, and others. *args: Positional arguments to pass to the source-specific method. **kwargs: Keyword arguments to pass to the source-specific method. Returns: A ScenarioList object created from the specified source. Examples:

classmethod from_urls(urls: list[str], field_name: str | None = ‘text’) → ScenarioList [source]

classmethod gen(scenario_dicts_list: List[dict]) → ScenarioList [source]

Create a ScenarioList from a list of dictionaries. Example:

get_tabular_data(remove_prefix: bool = False, pretty_labels: dict | None = None) → Tuple[List[str], List[List]][source]

Internal method to get tabular data in a standard format. Args: remove_prefix: Whether to remove the prefix from column names pretty_labels: Dictionary mapping original column names to pretty labels Returns: Tuple containing (header_row, data_rows)

ggplot2(ggplot_code: str, shape: str = ‘wide’, sql: str | None = None, remove_prefix: bool = True, debug: bool = False, height: float = 4, width: float = 6, factor_orders: dict | None = None)[source]

Create visualizations using R’s ggplot2 library. This method provides a bridge to R’s powerful ggplot2 visualization library, allowing you to create sophisticated plots directly from EDSL data structures.
Parameters:
ggplot_code: R code string containing ggplot2 commands shape: Data shape to use (“wide” or “long”) sql: Optional SQL query to transform data before visualization remove_prefix: Whether to remove prefixes (like “answer.”) from column names debug: Whether to display debugging information height: Plot height in inches width: Plot width in inches factor_orders: Dictionary mapping factor variables to their desired order
Returns:
A plot object that renders in Jupyter notebooks
Notes:
  • Requires R and the ggplot2 package to be installed
  • Data is automatically converted to a format suitable for ggplot2
  • The ggplot2 code should reference column names as they appear after any transformations from the shape and remove_prefix parameters
Examples:

give_valid_names(existing_codebook: dict = None) → ScenarioList [source]

Give valid names to the scenario keys, using an existing codebook if provided. Args: existing_codebook (dict, optional): Existing mapping of original keys to valid names. Defaults to None. Returns: ScenarioList: A new ScenarioList with valid variable names and updated codebook.

group_by(id_vars: List[str], variables: List[str], func: Callable) → ScenarioList [source]

Group the ScenarioList by id_vars and apply a function. Delegates to ScenarioListTransformer.group_by.

property has_jinja_braces*: bool*[source]

Check if any Scenario in the list contains values with Jinja template braces. This property checks all Scenarios in the list to determine if any contain string values with Jinja template syntax ({{ and }}). This is important for rendering templates and avoiding conflicts with other templating systems.
Returns:
True if any Scenario contains values with Jinja braces, False otherwise.
Examples:

inner_join(other: ScenarioList, by: str | list[str]) → ScenarioList [source]

Perform an inner join with another ScenarioList, following SQL join semantics. Args: other: The ScenarioList to join with by: String or list of strings representing the key(s) to join on. Cannot be empty. Returns: A new ScenarioList containing only scenarios that have matches in both ScenarioLists

insert(index, value)[source]

Insert value at index.

is_serializable()[source]

items()[source]

Make this class compatible with dict.items() by accessing first scenario items. This ensures the class works as a drop-in replacement for UserList in code that expects a dictionary-like interface. Returns: items view from the first scenario object if available, empty list otherwise

keep(*fields: str) → ScenarioList[source]

Keep only the specified fields in the scenarios. Parameters: fields – The fields to keep. Example:

left_join(other: ScenarioList, by: str | list[str]) → ScenarioList source

Perform a left join with another ScenarioList, following SQL join semantics. Args: other: The ScenarioList to join with by: String or list of strings representing the key(s) to join on. Cannot be empty.

make_tabular(remove_prefix: bool, pretty_labels: dict | None = None) → tuple[list, List[list]] source

Turn the results into a tabular format. Parameters: remove_prefix – Whether to remove the prefix from the column names.

mutate(new_var_string: str, functions_dict: dict[str, Callable] | None = None) → ScenarioList source

Return a new ScenarioList with a new variable added. Delegates to ScenarioListTransformer.mutate.

num_observations()[source]

Return the number of observations in the dataset.

offload(inplace: bool = False) → ScenarioList source

Offloads base64-encoded content from all scenarios in the list by replacing ‘base64_string’ fields with ‘offloaded’. This reduces memory usage.
Args:
inplace (bool): If True, modify the current scenario list. If False, return a new one.
Returns:
ScenarioList: The modified scenario list (either self or a new instance).

order_by(*fields: str, reverse: bool = False) → ScenarioList source

Order the scenarios by one or more fields. Delegates to ScenarioListTransformer.order_by.

property parameters*: set*[source]

Return the set of parameters in the ScenarioList Example:

pivot(id_vars: List[str] = None, var_name=‘variable’, value_name=‘value’) → ScenarioList source

Pivot the ScenarioList from long to wide format. Delegates to ScenarioListTransformer.pivot.
Print the results in a long format. >>> from edsl.results import Results >>> r = Results.example() >>> r.select(‘how_feeling’).print_long() answer.how_feeling: OK answer.how_feeling: Great answer.how_feeling: Terrible answer.how_feeling: OK

relevant_columns(data_type: str | None = None, remove_prefix: bool = False) → list[source]

Return the set of keys that are present in the dataset. Parameters:
  • data_type – The data type to filter by.
  • remove_prefix – Whether to remove the prefix from the column names.

remove_prefix()[source]

Returns a new Dataset with the prefix removed from all column names. The prefix is defined as everything before the first dot (.) in the column name. If removing prefixes would result in duplicate column names, an exception is raised.
Returns:
Dataset: A new Dataset with prefixes removed from column names
Raises:
ValueError: If removing prefixes would result in duplicate column names
Examples:
# Testing remove_prefix with duplicate column names raises DatasetValueError - tested in unit tests

rename(replacement_dict: dict) → ScenarioList [source ]

Rename the fields in the scenarios. Parameters: replacement_dict – A dictionary with the old names as keys and the new names as values. Example:

reorder_keys(new_order: List[str]) → ScenarioList [source ]

Reorder the keys in the scenarios. Delegates to ScenarioListTransformer.reorder_keys.

replace_names(new_names: list) → ScenarioList [source ]

Replace the field names in the scenarios with a new list of names.
Parameters:
new_names – A list of new field names to use.
Examples:

replace_values(replacements: dict) → ScenarioList [source ]

Create new scenarios with values replaced according to the provided replacement dictionary.
Args:
replacements (dict): Dictionary of values to replace {old_value: new_value}
Returns:
ScenarioList: A new ScenarioList with replaced values
Examples:

report(*fields: str | None, top_n: int | None = None, header_fields: List[str] | None = None, divider: bool = True, return_string: bool = False, format: str = ‘markdown’, filename: str | None = None) → str | Document | None [source ]

Generates a report of the results by iterating through rows.
Args:
*fields: The fields to include in the report. If none provided, all fields are used. top_n: Optional limit on the number of observations to include. header_fields: Optional list of fields to include in the main header instead of as sections. divider: If True, adds a horizontal rule between observations (markdown only). return_string: If True, returns the markdown string. If False (default in notebooks), only displays the markdown without returning. format: Output format - either “markdown” or “docx”. filename: If provided and format is “docx”, saves the document to this file.
Returns:
Depending on format and return_string: - For markdown: A string if return_string is True, otherwise None (displays in notebook) - For docx: A docx.Document object, or None if filename is provided (saves to file)
Examples:

report_from_template(template: str, *fields: str | None, top_n: int | None = None, remove_prefix: bool = True, return_string: bool = False, format: str = ‘text’, filename: str | None = None, separator: str = ‘\n\n’, observation_title_template: str | None = None, explode: bool = False, filestore: bool = False) → str | Document | List | FileStore | None [source ]

Generates a report using a Jinja2 template for each row in the dataset. This method renders a user-provided Jinja2 template for each observation in the dataset, with template variables populated from the row data. This allows for completely customized report formatting using pandoc for advanced output formats.
Args:
template: Jinja2 template string to render for each row *fields: The fields to include in template context. If none provided, all fields are used. top_n: Optional limit on the number of observations to include. remove_prefix: Whether to remove type prefixes (e.g., “answer.”) from field names in template context. return_string: If True, returns the rendered content. If False (default in notebooks), only displays the content without returning. format: Output format - one of “text”, “html”, “pdf”, or “docx”. Formats other than “text” require pandoc. filename: If provided, saves the rendered content to this file. For exploded output, this becomes a template (e.g., “report_{index}.html”). separator: String to use between rendered templates for each row (ignored when explode=True). observation_title_template: Optional Jinja2 template for observation titles. Defaults to “Observation ” where index is 1-based. Template has access to all row data plus ‘index’ and ‘index0’ variables. explode: If True, creates separate files for each observation instead of one combined file. filestore: If True, wraps the generated file(s) in FileStore object(s). If no filename is provided, creates temporary files. For exploded output, returns a list of FileStore objects.
Returns:
Depending on explode, format, return_string, and filestore: - For text format: String content or None (if displayed in notebook) - For html format: HTML string content or None (if displayed in notebook) - For docx format: Document object or None (if saved to file) - For pdf format: PDF bytes or None (if saved to file) - If explode=True: List of created filenames (when filename provided) or list of documents/content - If filestore=True: FileStore object(s) containing the generated file(s)
Notes:
  • Pandoc is required for HTML, PDF, and DOCX output formats
  • Templates are treated as Markdown for all non-text formats
  • PDF output uses XeLaTeX engine through pandoc
  • HTML output includes standalone document structure
Examples:

right_join(other: ScenarioList, by: str | list[str]) → ScenarioList [source ]

Perform a right join with another ScenarioList, following SQL join semantics.
Args:
other: The ScenarioList to join with by: String or list of strings representing the key(s) to join on. Cannot be empty.
Returns:
A new ScenarioList containing all right scenarios with matching left data added

sample(n: int, seed: str | None = None) → ScenarioList [source ]

Return a random sample from the ScenarioList

select(*fields: str) → ScenarioList [source ]

Select only specified fields from all scenarios in the list. This method applies the select operation to each scenario in the list, returning a new ScenarioList where each scenario contains only the specified fields.
Args:
*fields: Field names to select from each scenario.
Returns:
A new ScenarioList with each scenario containing only the selected fields.
Raises:
KeyError: If any specified field doesn’t exist in any scenario.
Examples:

shuffle(seed: str | None = None) → ScenarioList [source ]

Shuffle the ScenarioList.

sql(query: str, transpose: bool = None, transpose_by: str = None, remove_prefix: bool = True, shape: str = ‘wide’) → Dataset [source ]

Execute SQL queries on the dataset. This powerful method allows you to use SQL to query and transform your data, combining the expressiveness of SQL with EDSL’s data structures. It works by creating an in-memory SQLite database from your data and executing the query against it.
Parameters:
query: SQL query string to execute transpose: Whether to transpose the resulting table (rows become columns) transpose_by: Column to use as the new index when transposing remove_prefix: Whether to remove type prefixes (e.g., “answer.”) from column names shape: Data shape to use (“wide” or “long”)
  • “wide”: Default tabular format with columns for each field
  • “long”: Melted format with key-value pairs, useful for certain queries
Returns:
A Dataset object containing the query results
Notes:
  • The data is stored in a table named “self” in the SQLite database
  • In wide format, column names include their type prefix unless remove_prefix=True
  • In long format, the data is melted into columns: row_number, key, value, data_type
  • Complex objects like lists and dictionaries are converted to strings
Examples:

string_cat(key: str, addend: str, position: str = ‘suffix’, inplace: bool = False) → ScenarioList [source ]

Concatenate a string to a field across all Scenarios. Applies the same behavior as Scenario.string_cat to each Scenario in the list. By default, returns a new ScenarioList; set inplace=True to modify this list. Args: key: The key whose value will be concatenated in each Scenario. addend: The string to concatenate to the existing value. position: Either “suffix” (default) or “prefix”. inplace: If True, modify scenarios in place and return self. Returns: A ScenarioList with updated Scenarios. Raises: KeyError: If key is missing in any Scenario. TypeError: If any value under key is not a string. ValueError: If position is not “suffix” or “prefix”.

sum(field: str) → int [source ]

Sum the values of a field across all scenarios.

table(*fields: str, tablefmt: Literal[‘plain’, ‘simple’, ‘github’, ‘grid’, ‘fancy_grid’, ‘pipe’, ‘orgtbl’, ‘rst’, ‘mediawiki’, ‘html’, ‘latex’, ‘latex_raw’, ‘latex_booktabs’, ‘tsv’] | None = ‘rich’, pretty_labels: dict[str, str] | None = None) → str [source ]

Return the ScenarioList as a table.

tack_on(replacements: dict[str, Any], index: int = -1) → ScenarioList [source ]

Add a duplicate of an existing scenario with optional value replacements. This method duplicates the scenario at index (default -1 which refers to the last scenario), applies the key/value pairs provided in replacements, and returns a new ScenarioList with the modified scenario appended. Args: replacements: Mapping of field names to new values to overwrite in the cloned scenario. index: Index of the scenario to duplicate. Supports negative indexing just like normal Python lists (-1 is the last item). Returns: ScenarioList: A new ScenarioList containing all original scenarios plus the newly created one. Raises: ScenarioError: If the ScenarioList is empty, index is out of range, or if any key in replacements does not exist in the reference scenario.

tally(*fields: str | None, top_n: int | None = None, output=‘Dataset’) → dict | Dataset [source ]

Count frequency distributions of values in specified fields. This method tallies the occurrence of unique values within one or more fields, similar to a GROUP BY and COUNT in SQL. When multiple fields are provided, it performs cross-tabulation across those fields.
Parameters:
*fields: Field names to tally. If none provided, uses all available fields. top_n: Optional limit to return only the top N most frequent values. output: Format for results, either “Dataset” (recommended) or “dict”.
Returns:
By default, returns a Dataset with columns for the field(s) and a ‘count’ column. If output=”dict”, returns a dictionary mapping values to counts.
Notes:
  • For single fields, returns counts of each unique value
  • For multiple fields, returns counts of each unique combination of values
  • Results are sorted in descending order by count
  • Fields can be specified with or without their type prefix
Examples:
# Single field frequency count >>> r.select(‘how_feeling’).tally(‘answer.how_feeling’, output=”dict”) {‘OK’: 2, ‘Great’: 1, ‘Terrible’: 1} # Return as Dataset (default) >>> from edsl.dataset import Dataset >>> expected = Dataset([{‘answer.how_feeling’: [‘OK’, ‘Great’, ‘Terrible’]}, {‘count’: [2, 1, 1]}]) >>> r.select(‘how_feeling’).tally(‘answer.how_feeling’, output=”Dataset”) == expected True # Multi-field cross-tabulation - exact output varies based on data >>> result = r.tally(‘how_feeling’, ‘how_feeling_yesterday’) >>> ‘how_feeling’ in result.keys() and ‘how_feeling_yesterday’ in result.keys() and ‘count’ in result.keys() True

times(other: ScenarioList) → ScenarioList [source ]

Takes the cross product of two ScenarioLists. Example:

to(survey: ‘Survey’ | ‘QuestionBase’) → Jobs [source ]

Create a Jobs object from a ScenarioList and a Survey object. Parameters: survey – The Survey object to use for the Jobs object. Example: >>> from edsl import Survey, Jobs, ScenarioList # doctest: +SKIP >>> isinstance(ScenarioList.example().to(Survey.example()), Jobs) # doctest: +SKIP True

to_agent_blueprint(*, seed: int | None = None, cycle: bool = True, dimension_name_field: str = ‘dimension’, dimension_values_field: str = ‘dimension_values’, dimension_description_field: str | None = None) [source ]

Create an AgentBlueprint from this ScenarioList. Args: seed: Optional seed for deterministic permutation order. cycle: Whether to continue cycling through permutations indefinitely. dimension_name_field: Field name to read the dimension name from. dimension_values_field: Field name to read the dimension values from. dimension_description_field: Optional field name for the dimension description.

to_agent_list(remove_prefix: bool = True) [source ]

Convert the results to a list of dictionaries, one per agent. Parameters: remove_prefix – Whether to remove the prefix from the column names.

to_agent_traits(agent_name: str | None = None) → Agent [source ]

Convert all Scenario objects to traits of a single Agent. Delegates to ScenarioListTransformer.to_agent_traits.

to_csv(filename: str | None = None, remove_prefix: bool = False, pretty_labels: dict | None = None) → FileStore [source ]

Export the results to a FileStore instance containing CSV data.

to_dataset() → Dataset [source ]

Convert the ScenarioList to a Dataset.

to_dict(sort: bool = False, add_edsl_version: bool = False) → dict [source ]

to_dicts(remove_prefix: bool = True) → list[dict] [source ]

Convert the results to a list of dictionaries. Parameters: remove_prefix – Whether to remove the prefix from the column names.

to_docx(filename: str | None = None, remove_prefix: bool = False, pretty_labels: dict | None = None) → FileStore [source ]

Export the results to a FileStore instance containing DOCX data. Each row of the dataset will be rendered on its own page, with a 2-column table that lists the keys and associated values for that observation.

to_excel(filename: str | None = None, remove_prefix: bool = False, pretty_labels: dict | None = None, sheet_name: str | None = None) [source ]

Export the results to a FileStore instance containing Excel data.

to_jsonl(filename: str | None = None) [source ]

Export the results to a FileStore instance containing JSONL data.

to_key_value(field: str, value=None) → dict | set [source ]

Return the set of values in the field. Parameters:
  • field – The field to extract values from.
  • value – An optional field to use as the value in the key-value pair.
Example:

to_list(flatten=False, remove_none=False, unzipped=False) → list[list] [source ]

Convert the results to a list of lists. Parameters:
  • flatten – Whether to flatten the list of lists.
  • remove_none – Whether to remove None values from the list.

to_pandas(remove_prefix: bool = False, lists_as_strings=False) [source ]

Convert the results to a pandas DataFrame, ensuring that lists remain as lists. Args: remove_prefix: Whether to remove the prefix from the column names. lists_as_strings: Whether to convert lists to strings. Returns: A pandas DataFrame.

to_polars(remove_prefix: bool = False, lists_as_strings=False) [source ]

Convert the results to a Polars DataFrame. Args: remove_prefix: Whether to remove the prefix from the column names. lists_as_strings: Whether to convert lists to strings. Returns: A Polars DataFrame.

to_ranked_scenario_list(option_fields: Sequence[str], answer_field: str, include_rank: bool = True, rank_field: str = ‘rank’, item_field: str = ‘item’) → ScenarioList [source ]

Convert the ScenarioList to a ranked ScenarioList based on pairwise comparisons. Args: option_fields: List of scenario column names containing options to compare. answer_field: Name of the answer column containing the chosen option’s value. include_rank: If True, include a rank field on each returned Scenario. rank_field: Name of the rank field to include when include_rank is True. item_field: Field name used to store the ranked item value on each Scenario. Returns: ScenarioList ordered best-to-worst according to pairwise ranking.

to_scenario_list(remove_prefix: bool = True) → ScenarioList [source ]

Convert the results to a list of dictionaries, one per scenario. Parameters: remove_prefix – Whether to remove the prefix from the column names.

to_scenario_of_lists() → Scenario [source ]

Return a single Scenario whose values are lists across the list. The resulting Scenario contains every key that appears in any member of the list. For each key, the value is a list of that key’s values taken row-wise from the ScenarioList, padding with None when a row is missing the key.

to_sqlite(filename: str | None = None, remove_prefix: bool = False, pretty_labels: dict | None = None, table_name: str = ‘results’, if_exists: str = ‘replace’) [source ]

Export the results to a SQLite database file.

to_survey() → Survey [source ]

to_true_skill_ranked_list(option_fields: Sequence[str], answer_field: str, include_rank: bool = True, rank_field: str = ‘rank’, item_field: str = ‘item’, mu_field: str = ‘mu’, sigma_field: str = ‘sigma’, conservative_rating_field: str = ‘conservative_rating’, initial_mu: float = 25.0, initial_sigma: float = 8.333, beta: float = None, tau: float = None) → ScenarioList [source ]

Convert the ScenarioList to a ranked ScenarioList using TrueSkill algorithm. Args: option_fields: List of scenario column names containing options to compare. answer_field: Name of the answer column containing the ranking order. include_rank: If True, include a rank field on each returned Scenario. rank_field: Name of the rank field to include when include_rank is True. item_field: Field name used to store the ranked item value on each Scenario. mu_field: Field name for TrueSkill mu (skill estimate) value. sigma_field: Field name for TrueSkill sigma (uncertainty) value. conservative_rating_field: Field name for conservative rating (mu - 3*sigma). initial_mu: Initial skill rating (default 25.0). initial_sigma: Initial uncertainty (default 8.333). beta: Skill class width (defaults to initial_sigma/2). tau: Dynamics factor (defaults to initial_sigma/300).

Returns:

ScenarioList ordered best-to-worst according to TrueSkill ranking.

transform(field: str, func: Callable, new_name: str | None = None) → ScenarioList [source ]

Transform a field using a function. Delegates to ScenarioListTransformer.transform.

transform_by_key(key_field: str) → Scenario [source ]

Transform the ScenarioList into a single Scenario with key/value pairs. This method transforms the ScenarioList by: 1. Using the value of the specified key_field from each Scenario as a new key 2. Automatically formatting the remaining values as “key: value, key: value” 3. Creating a single Scenario containing all the transformed key/value pairs
Args:
key_field: The field name whose value will become the new key
Returns:
A single Scenario with all the transformed key/value pairs
Examples:
tree(node_order: List[str] | None = None) [source ]
Convert the results to a Tree. Args: node_order: The order of the nodes. Returns: A Tree object.
unique() → ScenarioList [source ]
Return a new ScenarioList containing only unique Scenario objects. This method removes duplicate Scenario objects based on their hash values, which are determined by their content. Two Scenarios with identical key-value pairs will have the same hash and be considered duplicates.
Returns:
A new ScenarioList containing only unique Scenario objects.
Examples:
Notes:
  • The order of scenarios in the result is not guaranteed due to the use of sets
  • Uniqueness is determined by the Scenario’s __hash__ method
  • The original ScenarioList is not modified
  • This implementation is memory efficient as it processes scenarios one at a time

unpack(field: str, new_names: List[str] | None = None, keep_original=True) → ScenarioList [source ]

Unpack a field into multiple fields. Delegates to ScenarioListTransformer.unpack.
unpack_dict(field: str, prefix: str | None = None, drop_field: bool = False) → ScenarioList [source ]
Unpack a dictionary field into separate fields. Delegates to ScenarioListTransformer.unpack_dict.

unpack_list(field: str, new_names: List[str] | None = None, keep_original: bool = True) → Dataset [source ]

Unpack list columns into separate columns with provided names or numeric suffixes. For example, if a dataset contains: [{ ‘data’: [[1, 2, 3], [4, 5, 6]], ‘other’: [‘x’, ‘y’]}] After d.unpack_list(‘data’), it should become: [{ ‘other’: [‘x’, ‘y’], ‘data_1’: [1, 4], ‘data_2’: [2, 5], ‘data_3’: [3, 6]}]
Args:
field: The field containing lists to unpack new_names: Optional list of names for the unpacked fields. If None, uses numeric suffixes. keep_original: If True, keeps the original field in the dataset
Returns:
A new Dataset with unpacked columns
Examples:
from edsl.dataset import Dataset

unpivot(id_vars: List[str] | None = None, value_vars: List[str] | None = None) → ScenarioList [source ]

Unpivot the ScenarioList, allowing for id variables. Delegates to ScenarioListTransformer.unpivot.

zip(field_a: str, field_b: str, new_name: str) → ScenarioList [source ]

Zip two iterable fields in each Scenario into a dict under a new key. For every Scenario in the list, this method computes dict(zip(scenario[field_a], scenario[field_b])) and stores the result in a new key named new_name. It returns a new ScenarioList containing the updated Scenarios.
Args:
field_a: Name of the first iterable field whose values become dict keys. field_b: Name of the second iterable field whose values become dict values. new_name: Name of the new field to store the resulting dictionary under.
Returns:
A new ScenarioList with the zipped dictionary added to each Scenario.
Raises:
KeyError: If either field name does not exist in any Scenario. ScenarioError: If referenced fields are not iterable in any Scenario.
Examples: