class documentation

An expression defining a possibly-complex manipulation of a document.

View expressions enable you to specify manipulations of documents that can then be executed on your data in the context of a fiftyone.core.stages.ViewStage.

Typically, ViewExpression instances are built by creating one or more ViewField instances and then defining the desired operation by recursively invoking methods on these objects:

from fiftyone import ViewField as F

# An expression that tests whether the `confidence` field of a document
# is greater than 0.9
F("confidence") > 0.9

# An expression that computes the area of a bounding box
# Bboxes are in [top-left-x, top-left-y, width, height] format
F("bounding_box")[2] * F("bounding_box")[3]

#
# A more complex expression that returns one of three strings based on
# the number of high confidence predictions in the `detections` field
# of a document with the label "cat" or "dog" after normalizing to
# lowercase
#
F("detections").map(
    F().set_field("label", F("label").lower())
).filter(
    F("label").is_in(("cat", "dog")) & (F("confidence") > 0.9)
).length().switch(
    {
        (F() >= 10): "zoo",
        (F() > 2) & (F() < 10): "party",
        (F() <= 2): "home",
    }
)

There are a few cases where you may need to instantitate a ViewExpression directly, typically when you need to write an expression that begins with a literal Python value:

from fiftyone import ViewExpression as E
from fiftyone import ViewField as F

# Concatenates the "-animal" string to the `label` field of a document
F("label").concat("-animal")

# Prepends the "animal-" string to the `label` field
E("animal-").concat(F("label"))

# Appends the strings "test" and "validation" to the contents of the
# `tags` field array
# assumed to be an array
F("tags").extend(["test", "validation"])

# Prepends the "test" and "validation" strings to the `tags` field
E(["test", "validation"]).extend(F("tags"))

See MongoDB expressions for more details about the underlying expression language that this class encapsulates.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
bbox_area = F("bounding_box")[2] * F("bounding_box")[3]

#
# Create a view that only contains predictions whose bounding boxes
# have area < 0.2 with confidence > 0.9, and only include samples with
# at least 15 such objects
#
view = dataset.filter_labels(
    "predictions",
    (bbox_area < 0.2) & (F("confidence") > 0.9)
).match(
    F("predictions.detections").length() > 15
)

session = fo.launch_app(view=view)
Parameters
exprthe MongoDB expression
Static Method all Checks whether all of the given expressions evaluate to True.
Static Method any Checks whether any of the given expressions evaluate to True.
Static Method enumerate Returns an array of [index, element] pairs enumerating the elements of the given expression, which must resolve to an array.
Static Method literal Returns an expression representing the given value without parsing.
Static Method rand Returns an expression that generates a uniform random float in [0, 1] each time it is called.
Static Method randn Returns an expression that generates a sample from the standard Gaussian distribution each time it is called.
Static Method range Returns an array expression containing the sequence of integers from the specified start (inclusive) to stop (exclusive).
Static Method zip Zips the given expressions, which must resolve to arrays, into an array whose ith element is an array containing the ith element from each input array.
Method __abs__ Computes the absolute value of this expression, which must resolve to a numeric value.
Method __add__ Adds the given value to this expression, which must resolve to a numeric value, self + other.
Method __and__ Computes the logical AND of this expression and the given value or expression, self & other.
Method __call__ Retrieves the specified field or embedded field of this expression, which must resolve to a document.
Method __ceil__ Computes the ceiling of this expression, which must resolve to a numeric value.
Method __deepcopy__ Undocumented
Method __eq__ Determines whether this expression is equal to the given value or expression, self == other.
Method __floor__ Computes the floor of this expression, which must resolve to a numeric value.
Method __ge__ Determines whether this expression is greater than or equal to the given value or expression, self >= other.
Method __getitem__ Returns the element or slice of this expression, which must resolve to an array.
Method __gt__ Determines whether this expression is greater than the given value or expression, self >= other.
Method __hash__ Undocumented
Method __init__ Undocumented
Method __invert__ Inverts this expression, ~self.
Method __le__ Determines whether this expression is less than or equal to the given value or expression, self <= other.
Method __len__ Undocumented
Method __lt__ Determines whether this expression is less than the given value or expression, self <= other.
Method __mod__ Computes the modulus of this expression, which must resolve to a numeric value, self % other.
Method __mul__ Computes the product of the given value and this expression, which must resolve to a numeric value, self * other.
Method __ne__ Determines whether this expression is not equal to the given value or expression, self != other.
Method __or__ Computes the logical OR of this expression and the given value or expression, self | other.
Method __pow__ Raises this expression, which must resolve to a numeric value, to the given power, self ** power.
Method __radd__ Undocumented
Method __rand__ Undocumented
Method __repr__ Undocumented
Method __rmod__ Undocumented
Method __rmul__ Undocumented
Method __ror__ Undocumented
Method __round__ Rounds this expression, which must resolve to a numeric value, at the given decimal place.
Method __rsub__ Undocumented
Method __rtruediv__ Undocumented
Method __str__ Undocumented
Method __sub__ Subtracts the given value from this expression, which must resolve to a numeric value, self - other.
Method __truediv__ Divides this expression, which must resolve to a numeric value, by the given value, self / other.
Method abs Computes the absolute value of this expression, which must resolve to a numeric value.
Method append Appends the given value to this expression, which must resolve to an array.
Method apply Applies the given expression to this expression.
Method arccos Computes the inverse cosine of this expression, which must resolve to a numeric value, in radians.
Method arccosh Computes the inverse hyperbolic cosine of this expression, which must resolve to a numeric value, in radians.
Method arcsin Computes the inverse sine of this expression, which must resolve to a numeric value, in radians.
Method arcsinh Computes the inverse hyperbolic sine of this expression, which must resolve to a numeric value, in radians.
Method arctan Computes the inverse tangent of this expression, which must resolve to a numeric value, in radians.
Method arctanh Computes the inverse hyperbolic tangent of this expression, which must resolve to a numeric value, in radians.
Method cases Applies a case statement to this expression, which effectively computes the following pseudocode:
Method ceil Computes the ceiling of this expression, which must resolve to a numeric value.
Method concat Concatenates the given string(s) to this expression, which must resolve to a string.
Method contains Checks whether this expression, which must resolve to an array, contains any of the given values.
Method contains_str Determines whether this expression, which must resolve to a string, contains the given string or string(s).
Method cos Computes the cosine of this expression, which must resolve to a numeric value, in radians.
Method cosh Computes the hyperbolic cosine of this expression, which must resolve to a numeric value, in radians.
Method day_of_month Returns the day of the month of this date expression (in UTC) as a number between 1 and 31.
Method day_of_week Returns the day of the week of this date expression (in UTC) as a number between 1 (Sunday) and 7 (Saturday).
Method day_of_year Returns the day of the year of this date expression (in UTC) as a number between 1 and 366.
Method difference Computes the set difference of this expression, which must resolve to an array, and the given array or array expression.
Method ends_with Determines whether this expression, which must resolve to a string, ends with the given string or string(s).
Method exists Determines whether this expression, which must resolve to a field, exists and is not None.
Method exp Raises Euler's number to this expression, which must resolve to a numeric value.
Method extend Concatenates the given array(s) or array expression(s) to this expression, which must resolve to an array.
Method filter Applies the given filter to the elements of this expression, which must resolve to an array.
Method floor Computes the floor of this expression, which must resolve to a numeric value.
Method hour Returns the hour portion of this date expression (in UTC) as a number between 0 and 23.
Method if_else Returns either true_expr or false_expr depending on the value of this expression, which must resolve to a boolean.
Method insert Inserts the value before the given index in this expression, which must resolve to an array.
Method intersection Computes the set intersection of this expression, which must resolve to an array, and the given array(s) or array expression(s).
Method is_array Determines whether this expression is an array.
Method is_in Creates an expression that returns a boolean indicating whether self in values.
Method is_missing Determines whether this expression refers to a missing field.
Method is_null Determines whether this expression is null.
Method is_number Determines whether this expression is a number.
Method is_string Determines whether this expression is a string.
Method is_subset Checks whether this expression's contents, which must resolve to an array, are a subset of the given array or array expression's contents.
Method join Joins the elements of this expression, which must resolve to a string array, by the given delimiter.
Method length Computes the length of this expression, which must resolve to an array.
Method let_in Returns an equivalent expression where this expression is defined as a variable that is used wherever necessary in the given expression.
Method ln Computes the natural logarithm of this expression, which must resolve to a numeric value.
Method log Computes the logarithm base base of this expression, which must resolve to a numeric value.
Method log10 Computes the logarithm base 10 of this expression, which must resolve to a numeric value.
Method lower Converts this expression, which must resolve to a string, to lowercase.
Method lstrip Removes whitespace characters from the beginning of this expression, which must resolve to a string.
Method map Applies the given expression to the elements of this expression, which must resolve to an array.
Method map_values Replaces this expression with the corresponding value in the provided mapping dict, if it is present as a key.
Method matches_str Determines whether this expression, which must resolve to a string, exactly matches the given string or string(s).
Method max Returns the maximum value of either this expression, which must resolve to an array, or the maximum of this expression and the given value.
Method mean Returns the average value in this expression, which must resolve to a numeric array.
Method millisecond Returns the millisecond portion of this date expression (in UTC) as an integer between 0 and 999.
Method min Returns the minimum value of either this expression, which must resolve to an array, or the minimum of this expression and the given value.
Method minute Returns the minute portion of this date expression (in UTC) as a number between 0 and 59.
Method month Returns the month of this date expression (in UTC) as a number between 1 and 12.
Method pow Raises this expression, which must resolve to a numeric value, to the given power, self ** power.
Method prepend Prepends the given value to this expression, which must resolve to an array.
Method re_match Performs a regular expression pattern match on this expression, which must resolve to a string.
Method reduce Applies the given reduction to this expression, which must resolve to an array, and returns the single value computed.
Method replace Replaces all occurrences of old with new in this expression, which must resolve to a string.
Method reverse Reverses the order of the elements in the expression, which must resolve to an array.
Method round Rounds this expression, which must resolve to a numeric value, at the given decimal place.
Method rsplit Splits this expression, which must resolve to a string, by the given delimiter.
Method rstrip Removes whitespace characters from the end of this expression, which must resolve to a string.
Method second Returns the second portion of this date expression (in UTC) as a number between 0 and 59.
Method set_equals Checks whether this expression, which must resolve to an array, contains the same distinct values as each of the given array(s) or array expression(s).
Method set_field Sets the specified field or embedded field of this expression, which must resolve to a document, to the given value or expression.
Method sin Computes the sine of this expression, which must resolve to a numeric value, in radians.
Method sinh Computes the hyperbolic sine of this expression, which must resolve to a numeric value, in radians.
Method sort Sorts this expression, which must resolve to an array.
Method split Splits this expression, which must resolve to a string, by the given delimiter.
Method sqrt Computes the square root of this expression, which must resolve to a numeric value.
Method starts_with Determines whether this expression, which must resolve to a string, starts with the given string or string(s).
Method std Returns the standard deviation of the values in this expression, which must resolve to a numeric array.
Method strip Removes whitespace characters from the beginning and end of this expression, which must resolve to a string.
Method strlen Computes the length of this expression, which must resolve to a string.
Method substr Extracts the specified substring from this expression, which must resolve to a string.
Method sum Returns the sum of the values in this expression, which must resolve to a numeric array.
Method switch Applies a switch statement to this expression, which effectively computes the given pseudocode:
Method tan Computes the tangent of this expression, which must resolve to a numeric value, in radians.
Method tanh Computes the hyperbolic tangent of this expression, which must resolve to a numeric value, in radians.
Method to_bool Converts the expression to a boolean value.
Method to_date Converts the expression to a date value.
Method to_double Converts the expression to a double precision value.
Method to_int Converts the expression to an integer value.
Method to_mongo Returns a MongoDB representation of the expression.
Method to_string Converts the expression to a string value.
Method trunc Truncates this expression, which must resolve to a numeric value, at the specified decimal place.
Method type Returns the type string of this expression.
Method union Computes the set union of this expression, which must resolve to an array, and the given array(s) or array expression(s).
Method unique Returns an array containing the unique values in this expression, which must resolve to an array.
Method upper Converts this expression, which must resolve to a string, to uppercase.
Method week Returns the week of the year of this date expression (in UTC) as a number between 0 and 53.
Method year Returns the year of this date expression (in UTC).
Property is_frozen Whether this expression's prefix is frozen.
Method _freeze_prefix Undocumented
Method _function Undocumented
Method _let_in Undocumented
Instance Variable _expr Undocumented
Instance Variable _prefix Undocumented

Checks whether all of the given expressions evaluate to True.

If no expressions are provided, returns True.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Create a view that only contains predictions that are "cat" and
# highly confident
is_cat = F("label") == "cat"
is_confident = F("confidence") > 0.95
view = dataset.filter_labels(
    "predictions", F.all([is_cat, is_confident])
)

print(dataset.count("predictions.detections"))
print(view.count("predictions.detections"))
Parameters
exprsa ViewExpression or iterable of ViewExpression instances
Returns
a ViewExpression

Checks whether any of the given expressions evaluate to True.

If no expressions are provided, returns False.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Create a view that only contains predictions that are "cat" or
# highly confident
is_cat = F("label") == "cat"
is_confident = F("confidence") > 0.95
view = dataset.filter_labels(
    "predictions", F.any([is_cat, is_confident])
)

print(dataset.count("predictions.detections"))
print(view.count("predictions.detections"))
Parameters
exprsa ViewExpression or iterable of ViewExpression instances
Returns
a ViewExpression
@staticmethod
def enumerate(array, start=0): (source)

Returns an array of [index, element] pairs enumerating the elements of the given expression, which must resolve to an array.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(filepath="image1.jpg", tags=["a", "b", "c"]),
        fo.Sample(filepath="image2.jpg", tags=["y", "z"]),
    ]
)

# Populates an `enumerated_tags` field with the enumerated `tag`
dataset.add_sample_field("enumerated_tags", fo.ListField)
view = dataset.set_field("enumerated_tags", F.enumerate(F("tags")))

print(view.first())
Parameters
arraya ViewExpression that resolves to an array
start:0the starting enumeration index to use
Returns
a ViewExpression
@staticmethod
def literal(value): (source)

Returns an expression representing the given value without parsing.

See this page for more information on when this method is required.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Add the "$money" tag to each sample
# The "$" character ordinarily has special meaning, so we must wrap
# it in `literal()` in order to add it via this method
view = dataset.set_field(
    "tags", F("tags").append(F.literal("$money"))
)

print(view.first().tags)
Parameters
valuea value
Returns
a ViewExpression

Returns an expression that generates a uniform random float in [0, 1] each time it is called.

Warning

This expression will generate new values each time it is used, so you likely do not want to use it to construct dataset views, since such views would produce different outputs each time they are used.

A typical usage for this expression is in conjunction with fiftyone.core.view.DatasetView.set_field and fiftyone.core.view.DatasetView.save to populate a randomized field on a dataset.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewExpression as E

dataset = foz.load_zoo_dataset("quickstart").clone()

#
# Populate a new `rand` field with random numbers
#

dataset.add_sample_field("rand", fo.FloatField)
dataset.set_field("rand", E.rand()).save("rand")

print(dataset.bounds("rand"))

#
# Create a view that contains a different 10%% of the dataset each
# time it is used
#

view = dataset.match(E.rand() < 0.1)

print(view.first().id)
print(view.first().id)  # probably different!
Returns
a ViewExpression

Returns an expression that generates a sample from the standard Gaussian distribution each time it is called.

Warning

This expression will generate new values each time it is used, so you likely do not want to use it to construct dataset views, since such views would produce different outputs each time they are used.

A typical usage for this expression is in conjunction with fiftyone.core.view.DatasetView.set_field and fiftyone.core.view.DatasetView.save to populate a randomized field on a dataset.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewExpression as E

dataset = foz.load_zoo_dataset("quickstart").clone()

#
# Populate a new `randn` field with random numbers
#

dataset.add_sample_field("randn", fo.FloatField)
dataset.set_field("randn", E.randn()).save("randn")

print(dataset.bounds("randn"))

#
# Create a view that contains a different 50%% of the dataset each
# time it is used
#

view = dataset.match(E.randn() < 0)

print(view.first().id)
print(view.first().id)  # probably different!
Returns
a ViewExpression
@staticmethod
def range(start, stop=None): (source)

Returns an array expression containing the sequence of integers from the specified start (inclusive) to stop (exclusive).

If stop is provided, returns [start, start + 1, ..., stop - 1].

If no stop is provided, returns [0, 1, ..., start - 1].

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(filepath="image1.jpg", tags=["a", "b", "c"]),
        fo.Sample(filepath="image2.jpg", tags=["y", "z"]),
    ]
)

# Populates an `ints` field based on the number of `tags`
dataset.add_sample_field("ints", fo.ListField)
view = dataset.set_field("ints", F.range(F("tags").length()))

print(view.first())
Parameters
startthe starting value, or stopping value if no stop is provided
stop:Nonethe stopping value, if both input arguments are provided
Returns
a ViewExpression
@staticmethod
def zip(*args, use_longest=False, defaults=None): (source)

Zips the given expressions, which must resolve to arrays, into an array whose ith element is an array containing the ith element from each input array.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(
            filepath="image1.jpg",
            tags=["a", "b", "c"],
            ints=[1, 2, 3, 4, 5],
        ),
        fo.Sample(
            filepath="image2.jpg",
            tags=["y", "z"],
            ints=[25, 26, 27, 28],
        ),
    ]
)

dataset.add_sample_field("tags_ints", fo.ListField)

# Populates an `tags_ints` field with the zipped `tags` and `ints`
view = dataset.set_field("tags_ints", F.zip(F("tags"), F("ints")))

print(view.first())

# Same as above but use the longest array to determine output size
view = dataset.set_field(
    "tags_ints",
    F.zip(F("tags"), F("ints"), use_longest=True, defaults=("", 0))
)

print(view.first())
Parameters
*argsone or more arrays or ViewExpression instances resolving to arrays
use_longest:Falsewhether to use the longest array to determine the number of elements in the output array. By default, the length of the shortest array is used
defaults:Nonean optional array of default values of same length as *args to use when use_longest == True and the input arrays are of different lengths. If no defaults are provided and use_longest == True, then missing values are set to None
Returns
a ViewExpression
def __abs__(self): (source)

Computes the absolute value of this expression, which must resolve to a numeric value.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with `uniqueness` in [0.25, 0.75]
view = dataset.match(abs(F("uniqueness") - 0.5) < 0.25)

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def __add__(self, other): (source)

Adds the given value to this expression, which must resolve to a numeric value, self + other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
manhattan_dist = F("bounding_box")[0] + F("bounding_box")[1]

# Only contains predictions whose bounding boxes' upper left corner
# is a Manhattan distance of at least 1 from the origin
dataset.filter_labels("predictions, manhattan_dist > 1)

print(dataset.count("predictions.detections"))
print(view.count("predictions.detections"))
Parameters
othera number or ViewExpression
Returns
a ViewExpression
def __and__(self, other): (source)

Computes the logical AND of this expression and the given value or expression, self & other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains predictions with label "cat" and confidence > 0.9
view = dataset.filter_labels(
    "predictions",
    (F("label") == "cat") & (F("confidence") > 0.9)
)

print(view.count_values("predictions.detections.label"))
print(view.bounds("predictions.detections.confidence"))
Parameters
othera literal value or ViewExpression
Returns
a ViewExpression
def __call__(self, field): (source)

Retrieves the specified field or embedded field of this expression, which must resolve to a document.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Sort samples alphabetically by the label of their first ground
# truth object
view = dataset.sort_by(F("ground_truth.detections")[0]("label"))

print(view.values(F("ground_truth.detections")[0]("label")))
Parameters
fielda "field" or "embedded.field.name"
Returns
a ViewExpression
def __ceil__(self): (source)

Computes the ceiling of this expression, which must resolve to a numeric value.

Examples:

import math

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with `uniqueness` in [0.5, 1]
view = dataset.match(math.ceil(F("uniqueness") + 0.5) == 2)

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def __deepcopy__(self, memo): (source)

Undocumented

def __eq__(self, other): (source)

Determines whether this expression is equal to the given value or expression, self == other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset(
    "cifar10", split="test", max_samples=500, shuffle=True
)

# Get samples whose ground truth `label` is "airplane"
view = dataset.match(F("ground_truth.label") == "airplane")

print(view.distinct("ground_truth.label"))
Parameters
othera literal value or ViewExpression
Returns
a ViewExpression
def __floor__(self): (source)

Computes the floor of this expression, which must resolve to a numeric value.

Examples:

import math

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with `uniqueness` in [0.5, 1]
view = dataset.match(math.floor(F("uniqueness") + 0.5) == 1)

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def __ge__(self, other): (source)

Determines whether this expression is greater than or equal to the given value or expression, self >= other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5
view = dataset.match(F("uniqueness") >= 0.5)

print(view.bounds("uniqueness"))
Parameters
othera literal value or ViewExpression
Returns
a ViewExpression
def __getitem__(self, idx_or_slice): (source)

Returns the element or slice of this expression, which must resolve to an array.

All of the typical slicing operations are supported, except for specifying a non-unit step:

expr[3]      # the fourth element
expr[-1]     # the last element
expr[:10]    # the first (up to) 10 elements
expr[-3:]    # the last (up to) 3 elements
expr[3:10]   # the fourth through tenth elements

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
bbox_area = F("bounding_box")[2] * F("bounding_box")[3]

# Only contains objects in the `predictions` field with area > 0.2
view = dataset.filter_labels("predictions", bbox_area > 0.2)

print(dataset.count("predictions.detections"))
print(view.count("predictions.detections"))
Parameters
idx_or_slicethe index or slice
Returns
a ViewExpression
def __gt__(self, other): (source)

Determines whether this expression is greater than the given value or expression, self >= other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is > 0.5
view = dataset.match(F("uniqueness") > 0.5)

print(view.bounds("uniqueness"))
Parameters
othera literal value or ViewExpression
Returns
a ViewExpression
def __hash__(self): (source)

Undocumented

def __invert__(self): (source)

Inverts this expression, ~self.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Add a new field to one sample
sample = dataset.first()
sample["new_field"] = ["hello", "there"]
sample.save()

# Get samples that do NOT have a value for `new_field`
view = dataset.match(~F("new_field").exists())

print(len(view))
Returns
a ViewExpression
def __le__(self, other): (source)

Determines whether this expression is less than or equal to the given value or expression, self <= other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is <= 0.5
view = dataset.match(F("uniqueness") <= 0.5)

print(view.bounds("uniqueness"))
Parameters
othera ViewExpression or a python primitive understood by MongoDB
Returns
a ViewExpression
def __len__(self): (source)

Undocumented

def __lt__(self, other): (source)

Determines whether this expression is less than the given value or expression, self <= other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is < 0.5
view = dataset.match(F("uniqueness") < 0.5)

print(view.bounds("uniqueness"))
Parameters
othera literal value or ViewExpression
Returns
a ViewExpression
def __mod__(self, other): (source)

Computes the modulus of this expression, which must resolve to a numeric value, self % other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with an even number of predictions
view = dataset.match(
    (F("predictions.detections").length() % 2) == 0
)

print(dataset.count("predictions.detections"))
print(view.count("predictions.detections"))
Parameters
othera number or ViewExpression
Returns
a ViewExpression
def __mul__(self, other): (source)

Computes the product of the given value and this expression, which must resolve to a numeric value, self * other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
bbox_area = F("bounding_box")[2] * F("bounding_box")[3]

# Only contains predictions whose bounding box area is > 0.2
view = dataset.filter_labels("predictions", bbox_area > 0.2)
Parameters
othera number or ViewExpression
Returns
a ViewExpression
def __ne__(self, other): (source)

Determines whether this expression is not equal to the given value or expression, self != other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset(
    "cifar10", split="test", max_samples=500, shuffle=True
)

# Get samples whose ground truth `label` is NOT "airplane"
view = dataset.match(F("ground_truth.label") != "airplane")

print("airplane" in view.distinct("ground_truth.label"))
Parameters
othera literal value or ViewExpression
Returns
a ViewExpression
def __or__(self, other): (source)

Computes the logical OR of this expression and the given value or expression, self | other.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains predictions with label "cat" or confidence > 0.9
view = dataset.filter_labels(
    "predictions",
    (F("label") == "cat") | (F("confidence") > 0.9)
)

print(view.count_values("predictions.detections.label"))
print(view.bounds("predictions.detections.confidence"))
Parameters
othera literal value or ViewExpression
Returns
a ViewExpression
def __pow__(self, power, modulo=None): (source)

Raises this expression, which must resolve to a numeric value, to the given power, self ** power.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
center_dist = (
    (F("bounding_box")[0] + 0.5 * F("bounding_box")[2] - 0.5) ** 2 +
    (F("bounding_box")[1] + 0.5 * F("bounding_box")[3] - 0.5) ** 2
).sqrt()

# Only contains predictions whose bounding box center is a distance
# of at most 0.02 from the center of the image
view = dataset.select_fields("predictions").filter_labels(
    "predictions", center_dist < 0.02
)

session = fo.launch_app(view=view)
Parameters
powerthe power
moduloUndocumented
Returns
a ViewExpression
def __radd__(self, other): (source)

Undocumented

def __rand__(self, other): (source)

Undocumented

def __repr__(self): (source)

Undocumented

def __rmod__(self, other): (source)

Undocumented

def __rmul__(self, other): (source)

Undocumented

def __ror__(self, other): (source)

Undocumented

def __round__(self, place=0): (source)

Rounds this expression, which must resolve to a numeric value, at the given decimal place.

Positive values of place will round to place decimal places:

place=2: 1234.5678 --> 1234.57

Negative values of place will round digits left of the decimal:

place=-2: 1234.5678 --> 1200

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with `uniqueness` in [0.25, 0.75]
view = dataset.match(round(2 * F("uniqueness")) == 1)

print(view.bounds("uniqueness"))
Parameters
place:0the decimal place at which to round. Must be an integer in range (-20, 100)
Returns
a ViewExpression
def __rsub__(self, other): (source)

Undocumented

def __rtruediv__(self, other): (source)

Undocumented

def __str__(self): (source)

Undocumented

def __sub__(self, other): (source)

Subtracts the given value from this expression, which must resolve to a numeric value, self - other.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")
dataset.compute_metadata()

# Bboxes are in [top-left-x, top-left-y, width, height] format
rectangleness = abs(
    F("$metadata.width") * F("bounding_box")[2] -
    F("$metadata.height") * F("bounding_box")[3]
)

# Only contains predictions whose bounding boxes are within 1 pixel
# of being square
view = (
    dataset
    .select_fields("predictions")
    .filter_labels("predictions", rectangleness <= 1)
)

session = fo.launch_app(view=view)
Parameters
othera number or ViewExpression
Returns
a ViewExpression
def __truediv__(self, other): (source)

Divides this expression, which must resolve to a numeric value, by the given value, self / other.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")
dataset.compute_metadata()

# Bboxes are in [top-left-x, top-left-y, width, height] format
aspect_ratio = (
    (F("$metadata.width") * F("bounding_box")[2]) /
    (F("$metadata.height") * F("bounding_box")[3])
)

# Only contains predictions whose aspect ratio is > 2
view = (
    dataset
    .select_fields("predictions")
    .filter_labels("predictions", aspect_ratio > 2)
)

session = fo.launch_app(view=view)
Parameters
othera number or ViewExpression
Returns
a ViewExpression
def abs(self): (source)

Computes the absolute value of this expression, which must resolve to a numeric value.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with `uniqueness` in [0.25, 0.75]
view = dataset.match((F("uniqueness") - 0.5).abs() < 0.25)

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def append(self, value): (source)

Appends the given value to this expression, which must resolve to an array.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(filepath="image1.jpg", tags=["a", "b"]),
        fo.Sample(filepath="image2.jpg", tags=["a", "b"]),
    ]
)

# Appends the "c" tag to each sample
view = dataset.set_field("tags", F("tags").append("c"))

print(view.first().tags)
Parameters
valuethe value or ViewExpression
Returns
a ViewExpression
def apply(self, expr): (source)

Applies the given expression to this expression.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples with `uniqueness` in [0.25, 0.75]
view = dataset.match(
    F("uniqueness").apply((F() > 0.25) & (F() < 0.75))
)

print(view.bounds("uniqueness"))
Parameters
expra ViewExpression
Returns
a ViewExpression
def arccos(self): (source)

Computes the inverse cosine of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `arccos()`
view = dataset.match(F("uniqueness").arccos() <= np.arccos(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def arccosh(self): (source)

Computes the inverse hyperbolic cosine of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `arccosh()`
view = dataset.match((1 + F("uniqueness")).arccosh() >= np.arccosh(1.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def arcsin(self): (source)

Computes the inverse sine of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `arcsin()`
view = dataset.match(F("uniqueness").arcsin() >= np.arcsin(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def arcsinh(self): (source)

Computes the inverse hyperbolic sine of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `arcsinh()`
view = dataset.match(F("uniqueness").arcsinh() >= np.arcsinh(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def arctan(self): (source)

Computes the inverse tangent of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `arctan()`
view = dataset.match(F("uniqueness").arctan() >= np.arctan(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def arctanh(self): (source)

Computes the inverse hyperbolic tangent of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `arctanh()`
view = dataset.match(F("uniqueness").arctanh() >= np.arctanh(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def cases(self, mapping, default=None): (source)

Applies a case statement to this expression, which effectively computes the following pseudocode:

for key, value in mapping.items():
    if self == key:
        return value

if default is not None:
    return default

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Set `uniqueness` values below 0.75 to None
view = dataset.set_field(
    "uniqueness",
    (F("uniqueness") > 0.75).if_else(F("uniqueness"), None)
)

# Map numeric `uniqueness` values to 1 and null values to 0
cases_view = view.set_field(
    "uniqueness",
    F("uniqueness").type().cases({"double": 1, "null": 0}),
)

print(cases_view.count_values("uniqueness"))
Parameters
mappinga dict mapping literals or ViewExpression keys to literal or ViewExpression values
default:Nonean optional literal or ViewExpression to return if none of the switch branches are taken
Returns
a ViewExpression
def ceil(self): (source)

Computes the ceiling of this expression, which must resolve to a numeric value.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with `uniqueness` in [0.5, 1]
view = dataset.match((F("uniqueness") + 0.5).ceil() == 2)

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def concat(self, *args): (source)

Concatenates the given string(s) to this expression, which must resolve to a string.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Appends "-tag" to all tags
transform_tag = F().concat("-tag")
view = dataset.set_field("tags", F("tags").map(transform_tag))

print(dataset.distinct("tags"))
print(view.distinct("tags"))
Parameters
*argsone or more strings or string ViewExpression instances
before:Falsewhether to position args before this string in the output string
Returns
a ViewExpression
def contains(self, values, all=False): (source)

Checks whether this expression, which must resolve to an array, contains any of the given values.

Pass all=True to require that this expression contains all of the given values.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")
print(dataset.count())

# Only contains samples with a "cat" prediction
view = dataset.match(
    F("predictions.detections.label").contains("cat")
)
print(view.count())

# Only contains samples with "cat" or "dog" predictions
view = dataset.match(
    F("predictions.detections.label").contains(["cat", "dog"])
)
print(view.count())

# Only contains samples with "cat" and "dog" predictions
view = dataset.match(
    F("predictions.detections.label").contains(["cat", "dog"], all=True)
)
print(view.count())
Parameters
valuesa value, iterable of values, or ViewExpression that resolves to an array of values
all:Falsewhether this expression must contain all (True) or any (False) of the given values
Returns
a ViewExpression
def contains_str(self, str_or_strs, case_sensitive=True): (source)

Determines whether this expression, which must resolve to a string, contains the given string or string(s).

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains predictions whose `label` contains "be"
view = dataset.filter_labels(
    "predictions", F("label").contains_str("be")
)

print(view.distinct("predictions.detections.label"))
Parameters
str_or_strsa string or iterable of strings
case_sensitive:Truewhether to perform a case sensitive match
Returns
a ViewExpression
def cos(self): (source)

Computes the cosine of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `cos()`
view = dataset.match(F("uniqueness").cos() <= np.cos(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def cosh(self): (source)

Computes the hyperbolic cosine of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `cosh()`
view = dataset.match(F("uniqueness").cosh() >= np.cosh(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def day_of_month(self): (source)

Returns the day of the month of this date expression (in UTC) as a number between 1 and 31.

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 2),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 3),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 4),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the days of the month for the dataset
print(dataset.values(F("created_at").day_of_month()))

# Samples with even days of the month
view = dataset.match(F("created_at").day_of_month() % 2 == 0)
print(len(view))
Returns
a ViewExpression
def day_of_week(self): (source)

Returns the day of the week of this date expression (in UTC) as a number between 1 (Sunday) and 7 (Saturday).

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 4),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 5),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 6),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 7),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the days of the week for the dataset
print(dataset.values(F("created_at").day_of_week()))

# Samples with even days of the week
view = dataset.match(F("created_at").day_of_week() % 2 == 0)
print(len(view))
Returns
a ViewExpression
def day_of_year(self): (source)

Returns the day of the year of this date expression (in UTC) as a number between 1 and 366.

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 2),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 3),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 4),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the days of the year for the dataset
print(dataset.values(F("created_at").day_of_year()))

# Samples with even days of the year
view = dataset.match(F("created_at").day_of_year() % 2 == 0)
print(len(view))
Returns
a ViewExpression
def difference(self, values): (source)

Computes the set difference of this expression, which must resolve to an array, and the given array or array expression.

The arrays are treated as sets, so all duplicates are removed.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(
            filepath="image1.jpg",
            tags=["a", "b"],
            other_tags=["a", "c"]
        )
    ]
)

print(dataset.values(F("tags").difference(F("other_tags"))))
# [['b']]
Parameters
valuesan iterable of values or a ViewExpression that resolves to an array
Returns
a ViewExpression
def ends_with(self, str_or_strs, case_sensitive=True): (source)

Determines whether this expression, which must resolve to a string, ends with the given string or string(s).

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose images are JPEGs or PNGs
view = dataset.match(F("filepath").ends_with((".jpg", ".png")))

print(view.count())
print(view.first().filepath)
Parameters
str_or_strsa string or iterable of strings
case_sensitive:Truewhether to perform a case sensitive match
Returns
a ViewExpression
def exists(self, bool=True): (source)

Determines whether this expression, which must resolve to a field, exists and is not None.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset(
    "quickstart", dataset_name=fo.get_default_dataset_name()
)

# Add a new field to one sample
sample = dataset.first()
sample["new_field"] = ["hello", "there"]
sample.save()

# Get samples that have a value for `new_field`
view = dataset.match(F("new_field").exists())

print(len(view))
Parameters
bool:Truewhether to determine whether this expression exists (True) or is None or non-existent (False)
Returns
a ViewExpression
def exp(self): (source)

Raises Euler's number to this expression, which must resolve to a numeric value.

Returns
a ViewExpression
def extend(self, *args): (source)

Concatenates the given array(s) or array expression(s) to this expression, which must resolve to an array.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(filepath="image1.jpg", tags=["a", "b"]),
        fo.Sample(filepath="image2.jpg", tags=["a", "b"]),
    ]
)

# Adds the "c" and "d" tags to each sample
view = dataset.set_field("tags", F("tags").extend(["c", "d"]))

print(view.first().tags)
Parameters
*argsone or more arrays or ViewExpression instances that resolve to array expressions
Returns
a ViewExpression
def filter(self, expr): (source)

Applies the given filter to the elements of this expression, which must resolve to an array.

The output array will only contain elements of the input array for which expr returns True.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only include predictions with `confidence` of at least 0.9
view = dataset.set_field(
    "predictions.detections",
    F("detections").filter(F("confidence") > 0.9)
)

print(view.bounds("predictions.detections.confidence"))
Parameters
expra ViewExpression that returns a boolean
Returns
a ViewExpression
def floor(self): (source)

Computes the floor of this expression, which must resolve to a numeric value.

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with `uniqueness` in [0.5, 1]
view = dataset.match((F("uniqueness") + 0.5).floor() == 1)

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def hour(self): (source)

Returns the hour portion of this date expression (in UTC) as a number between 0 and 23.

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 2),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 3),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 4),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the hour portion of the dates in the dataset
print(dataset.values(F("created_at").hour()))

# Samples with even hours
view = dataset.match(F("created_at").hour() % 2 == 0)
print(len(view))
Returns
a ViewExpression
def if_else(self, true_expr, false_expr): (source)

Returns either true_expr or false_expr depending on the value of this expression, which must resolve to a boolean.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Set `uniqueness` values below 0.75 to None
view = dataset.set_field(
    "uniqueness",
    (F("uniqueness") > 0.75).if_else(F("uniqueness"), None)
)

print(view.bounds("uniqueness"))
Parameters
true_expra ViewExpression or MongoDB expression dict
false_expra ViewExpression or MongoDB expression dict
Returns
a ViewExpression
def insert(self, index, value): (source)

Inserts the value before the given index in this expression, which must resolve to an array.

If index <= 0, the value is prepended to this array. If index >= self.length(), the value is appended to this array.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(filepath="image1.jpg", tags=["a", "c"]),
        fo.Sample(filepath="image2.jpg", tags=["a", "c"]),
    ]
)

# Adds the "ready" tag to each sample
view = dataset.set_field("tags", F("tags").insert(1, "b"))

print(view.first().tags)
Parameters
indexthe index at which to insert the value
valuethe value or ViewExpression
Returns
a ViewExpression
def intersection(self, *args): (source)

Computes the set intersection of this expression, which must resolve to an array, and the given array(s) or array expression(s).

The arrays are treated as sets, so all duplicates are removed.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(
            filepath="image1.jpg",
            tags=["a", "b"],
            other_tags=["a", "c"]
        )
    ]
)

print(dataset.values(F("tags").intersection(F("other_tags"))))
# [['a']]
Parameters
*argsone or more arrays or ViewExpression instances that resolve to array expressions
Returns
a ViewExpression
def is_array(self): (source)

Determines whether this expression is an array.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Verify that tags are arrays
view = dataset.match(F("tags").is_array())

print(len(view))
Returns
ViewExpression
def is_in(self, values): (source)

Creates an expression that returns a boolean indicating whether self in values.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

ANIMALS = [
    "bear", "bird", "cat", "cow", "dog", "elephant", "giraffe",
    "horse", "sheep", "zebra"
]

dataset = foz.load_zoo_dataset("quickstart")

# Create a view that only contains animal predictions
view = dataset.filter_labels(
    "predictions", F("label").is_in(ANIMALS)
)

print(view.count_values("predictions.detections.label"))
Parameters
valuesa value or iterable of values
Returns
a ViewExpression
def is_missing(self): (source)

Determines whether this expression refers to a missing field.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Verify that `foobar` is a non-existent field on all samples
view = dataset.match(F("foobar").is_missing())

print(len(view) == len(dataset))
Returns
ViewExpression
def is_null(self): (source)

Determines whether this expression is null.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Set `uniqueness` values below 0.25 to None
view = dataset.set_field(
    "uniqueness",
    (F("uniqueness") >= 0.25).if_else(F("uniqueness"), None)
)

# Create view that only contains samples with uniqueness = None
not_unique_view = view.match(F("uniqueness").is_null())

print(len(not_unique_view))
Returns
ViewExpression
def is_number(self): (source)

Determines whether this expression is a number.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Set `uniqueness` values below 0.25 to None
view = dataset.set_field(
    "uniqueness",
    (F("uniqueness") >= 0.25).if_else(F("uniqueness"), None)
)

# Create view that only contains samples with uniqueness values
has_unique_view = view.match(F("uniqueness").is_number())

print(len(has_unique_view))
Returns
ViewExpression
def is_string(self): (source)

Determines whether this expression is a string.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Verify that filepaths are strings
view = dataset.match(F("filepath").is_string())

print(len(view))
Returns
ViewExpression
def is_subset(self, values): (source)

Checks whether this expression's contents, which must resolve to an array, are a subset of the given array or array expression's contents.

The arrays are treated as sets, so duplicate values are ignored.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(
            filepath="image1.jpg",
            tags=["a", "b", "a", "b"],
            other_tags=["a", "b", "c"],
        )
    ]
)

print(dataset.values(F("tags").is_subset(F("other_tags"))))
# [True]
Parameters
valuesan iterable of values or a ViewExpression that resolves to an array
Returns
a ViewExpression
def join(self, delimiter): (source)

Joins the elements of this expression, which must resolve to a string array, by the given delimiter.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Generate a `list,of,labels` for the `predictions` of each sample
view = dataset.set_field(
    "predictions.labels",
    F("detections").map(F("label")).join(",")
)

print(view.first().predictions.labels)
Parameters
delimiterthe delimiter string
Returns
a ViewExpression
def length(self): (source)

Computes the length of this expression, which must resolve to an array.

If this expression's value is null or missing, zero is returned.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with at least 15 predicted objects
view = dataset.match(F("predictions.detections").length() >= 15)

print(dataset.count())
print(view.count())
Returns
a ViewExpression
def let_in(self, expr): (source)

Returns an equivalent expression where this expression is defined as a variable that is used wherever necessary in the given expression.

This method is useful when expr contains multiple instances of this expression, since it avoids duplicate computation of this expression in the final pipeline.

If expr is a simple expression such as a ViewField, no variable is defined and expr is directly returned.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
bbox_area = F("bounding_box")[2] * F("bounding_box")[3]

good_bboxes = (bbox_area > 0.25) & (bbox_area < 0.75)

# Optimize the expression
good_bboxes_opt = bbox_area.let_in(good_bboxes)

# Contains predictions whose bounding box areas are in [0.25, 0.75]
view = dataset.filter_labels("predictions", good_bboxes_opt)

print(good_bboxes)
print(good_bboxes_opt)
print(dataset.count("predictions.detections"))
print(view.count("predictions.detections"))
Parameters
expra ViewExpression
Returns
a ViewExpression
def ln(self): (source)

Computes the natural logarithm of this expression, which must resolve to a numeric value.

Examples:

import math

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5
view = dataset.match(F("uniqueness").ln() >= math.log(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def log(self, base): (source)

Computes the logarithm base base of this expression, which must resolve to a numeric value.

Examples:

import math

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5
view = dataset.match(F("uniqueness").log(2) >= math.log2(0.5))

print(view.bounds("uniqueness"))
Parameters
basethe logarithm base
Returns
a ViewExpression
def log10(self): (source)

Computes the logarithm base 10 of this expression, which must resolve to a numeric value.

Examples:

import math

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5
view = dataset.match(F("uniqueness").log10() >= math.log10(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def lower(self): (source)

Converts this expression, which must resolve to a string, to lowercase.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Converts all tags to lowercase
transform_tag = F().lower()
view = dataset.set_field("tags", F("tags").map(transform_tag))

print(dataset.distinct("tags"))
print(view.distinct("tags"))
Returns
a ViewExpression
def lstrip(self, chars=None): (source)

Removes whitespace characters from the beginning of this expression, which must resolve to a string.

If chars is provided, those characters are removed instead of whitespace.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewExpression as E
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Adds and then strips whitespace from the beginning of each tag
transform_tag = E(" ").concat(F()).lstrip()
view = dataset.set_field("tags", F("tags").map(transform_tag))

print(dataset.distinct("tags"))
print(view.distinct("tags"))
Parameters
chars:Nonean optional string or ViewExpression resolving to a string expression specifying characters to remove
Returns
a ViewExpression
def map(self, expr): (source)

Applies the given expression to the elements of this expression, which must resolve to an array.

The output will be an array with the applied results.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
bbox_area = F("bounding_box")[2] * F("bounding_box")[3]

# Only include predictions with `confidence` of at least 0.9
view = dataset.set_field(
    "predictions.detections",
    F("detections").map(F().set_field("area", bbox_area))
)

print(view.bounds("predictions.detections.area"))
Parameters
expra ViewExpression
Returns
a ViewExpression
def map_values(self, mapping): (source)

Replaces this expression with the corresponding value in the provided mapping dict, if it is present as a key.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

ANIMALS = [
    "bear", "bird", "cat", "cow", "dog", "elephant", "giraffe",
    "horse", "sheep", "zebra"
]

dataset = foz.load_zoo_dataset("quickstart")

#
# Replace the `label` of all animal objects in the `predictions`
# field with "animal"
#
mapping = {a: "animal" for a in ANIMALS}
view = dataset.set_field(
    "predictions.detections",
    F("detections").map(
        F().set_field("label", F("label").map_values(mapping))
    )
)

print(view.count_values("predictions.detections.label"))
Parameters
mappinga dict mapping keys to replacement values
Returns
a ViewExpression
def matches_str(self, str_or_strs, case_sensitive=True): (source)

Determines whether this expression, which must resolve to a string, exactly matches the given string or string(s).

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains predictions whose `label` is "cat" or "dog", case
# insensitive
view = dataset.map_labels(
    "predictions", {"cat": "CAT", "dog": "DOG"}
).filter_labels(
    "predictions",
    F("label").matches_str(("cat", "dog"), case_sensitive=False)
)

print(view.distinct("predictions.detections.label"))
Parameters
str_or_strsa string or iterable of strings
case_sensitive:Truewhether to perform a case sensitive match
Returns
a ViewExpression
def max(self, value=None): (source)

Returns the maximum value of either this expression, which must resolve to an array, or the maximum of this expression and the given value.

Missing or None values are ignored.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
bbox_area = F("bounding_box")[2] * F("bounding_box")[3]

# Adds a `max_area` property to the `predictions` field that
# records the maximum prediction area in that sample
view = dataset.set_field(
    "predictions.max_area",
    F("detections").map(bbox_area).max()
)

print(view.bounds("predictions.max_area"))
Parameters
value:Nonean optional value to compare to
Returns
a ViewExpression
def mean(self): (source)

Returns the average value in this expression, which must resolve to a numeric array.

Missing or None-valued elements are ignored.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Add a field to each `predictions` object that records the average
# confidence of the predictions
view = dataset.set_field(
    "predictions.conf_mean",
    F("detections").map(F("confidence")).mean()
)

print(view.bounds("predictions.conf_mean"))
Returns
a ViewExpression
def millisecond(self): (source)

Returns the millisecond portion of this date expression (in UTC) as an integer between 0 and 999.

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 0, 0, 1000),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 0, 0, 2000),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 0, 0, 3000),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 0, 0, 4000),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the millisecond portion of the dates in the dataset
print(dataset.values(F("created_at").millisecond()))

# Samples with even milliseconds
view = dataset.match(F("created_at").millisecond() % 2 == 0)
print(len(view))
Returns
a ViewExpression
def min(self, value=None): (source)

Returns the minimum value of either this expression, which must resolve to an array, or the minimum of this expression and the given value.

Missing or None values are ignored.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
bbox_area = F("bounding_box")[2] * F("bounding_box")[3]

# Adds a `min_area` property to the `predictions` field that
# records the minimum prediction area in that sample
view = dataset.set_field(
    "predictions.min_area",
    F("detections").map(bbox_area).min()
)

print(view.bounds("predictions.min_area"))
Parameters
value:Nonean optional value to compare to
Returns
a ViewExpression
def minute(self): (source)

Returns the minute portion of this date expression (in UTC) as a number between 0 and 59.

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 2),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 3),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 4),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the minute portion of the dates in the dataset
print(dataset.values(F("created_at").minute()))

# Samples with even minutes
view = dataset.match(F("created_at").minute() % 2 == 0)
print(len(view))
Returns
a ViewExpression
def month(self): (source)

Returns the month of this date expression (in UTC) as a number between 1 and 12.

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 2, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 3, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 4, 1),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the months of the year for the dataset
print(dataset.values(F("created_at").month()))

# Samples from even months of the year
view = dataset.match(F("created_at").month() % 2 == 0)
print(len(view))
Returns
a ViewExpression
def pow(self, power): (source)

Raises this expression, which must resolve to a numeric value, to the given power, self ** power.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
center_dist = (
    (F("bounding_box")[0] + 0.5 * F("bounding_box")[2] - 0.5).pow(2) +
    (F("bounding_box")[1] + 0.5 * F("bounding_box")[3] - 0.5).pow(2)
).sqrt()

# Only contains predictions whose bounding box center is a distance
# of at most 0.02 from the center of the image
view = dataset.select_fields("predictions").filter_labels(
    "predictions", center_dist < 0.02
)

session = fo.launch_app(view=view)
Parameters
powerthe power
Returns
a ViewExpression
def prepend(self, value): (source)

Prepends the given value to this expression, which must resolve to an array.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(filepath="image1.jpg", tags=["b", "c"]),
        fo.Sample(filepath="image2.jpg", tags=["b", "c"]),
    ]
)

# Adds the "a" tag to each sample
view = dataset.set_field("tags", F("tags").prepend("a"))

print(view.first().tags)
Parameters
valuethe value or ViewExpression
Returns
a ViewExpression
def re_match(self, regex, options=None): (source)

Performs a regular expression pattern match on this expression, which must resolve to a string.

The output of the expression will be True if the pattern matches and False otherwise.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

#
# Get samples whose images are JPEGs
#

view = dataset.match(F("filepath").re_match("\.jpg$"))

print(view.count())
print(view.first().filepath)

#
# Get samples whose images are in the "/Users" directory
#

view = dataset.match(F("filepath").re_match("^/Users/"))

print(view.count())
print(view.first().filepath)
Parameters
regexthe regular expression to apply. Must be a Perl Compatible Regular Expression (PCRE). See this page for details
options:Nonean optional string of regex options to apply. See this page for the available options
Returns
a ViewExpression
def reduce(self, expr, init_val=0): (source)

Applies the given reduction to this expression, which must resolve to an array, and returns the single value computed.

The provided expr must include the VALUE expression to properly define the reduction.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F
from fiftyone.core.expressions import VALUE

#
# Compute the number of keypoints in each sample of a dataset
#

dataset = fo.Dataset()
dataset.add_sample(
    fo.Sample(
        filepath="image.jpg",
        keypoints=fo.Keypoints(
            keypoints=[
                fo.Keypoint(points=[(0, 0), (1, 1)]),
                fo.Keypoint(points=[(0, 0), (1, 0), (1, 1), (0, 1)]),
            ]
        )
    )
)

view = dataset.set_field(
    "keypoints.count",
    F("$keypoints.keypoints").reduce(VALUE + F("points").length()),
)

print(view.first().keypoints.count)

#
# Generate a `list,of,labels` for the `predictions` of each sample
#

dataset = foz.load_zoo_dataset("quickstart")

join_labels = F("detections").reduce(
    VALUE.concat(",", F("label")), init_val=""
).lstrip(",")

view = dataset.set_field("predictions.labels", join_labels)

print(view.first().predictions.labels)
Parameters
expra ViewExpression defining the reduction expression to apply. Must contain the VALUE expression
init_val:0an initial value for the reduction
Returns
a ViewExpression
def replace(self, old, new): (source)

Replaces all occurrences of old with new in this expression, which must resolve to a string.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Replaces "val" with "VAL" in each tag
transform_tag = F().replace("val", "VAL")
view = dataset.set_field("tags", F("tags").map(transform_tag))

print(dataset.distinct("tags"))
print(view.distinct("tags"))
Parameters
olda string or ViewExpression resolving to a string expression specifying the substring to replace
newa string or ViewExpression resolving to a string expression specifying the replacement value
Returns
a ViewExpression
def reverse(self): (source)

Reverses the order of the elements in the expression, which must resolve to an array.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

first_obj = F("predictions.detections")[0]
last_obj = F("predictions.detections").reverse()[0]

# Only contains samples whose first and last prediction have the
# same label
view = dataset.match(
    first_obj.apply(F("label")) == last_obj.apply(F("label"))
)

print(dataset.count())
print(view.count())
Returns
a ViewExpression
def round(self, place=0): (source)

Rounds this expression, which must resolve to a numeric value, at the given decimal place.

Positive values of place will round to place decimal places:

place=2: 1234.5678 --> 1234.57

Negative values of place will round place digits left of the decimal:

place=-1: 1234.5678 --> 1230

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Only contains samples with `uniqueness` in [0.25, 0.75]
view = dataset.match((2 * F("uniqueness")).round() == 1)

print(view.bounds("uniqueness"))
Parameters
place:0the decimal place at which to round. Must be an integer in range (-20, 100)
Returns
a ViewExpression
def rsplit(self, delimiter, maxsplit=None): (source)

Splits this expression, which must resolve to a string, by the given delimiter.

If the number of chunks exceeds maxsplit, splits are only performed on the last maxsplit occurrences of the delimiter.

The result is a string array that contains the chunks with the delimiter removed. If the delimiter is not found, this full string is returned as a single element array.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Add "-ok-go" to the first tag and then split once on "-" from the
# right to create two tags for each sample
view = dataset.set_field(
    "tags", F("tags")[0].concat("-ok-go").rsplit("-", 1)
)

print(view.first().tags)
Parameters
delimiterthe delimiter string or ViewExpression resolving to a string expression
maxsplit:Nonea maximum number of splits to perform, from the right
Returns
a ViewExpression
def rstrip(self, chars=None): (source)

Removes whitespace characters from the end of this expression, which must resolve to a string.

If chars is provided, those characters are removed instead of whitespace.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Adds and then strips whitespace from the end of each tag
transform_tag = F().concat(" ").rstrip()
view = dataset.set_field("tags", F("tags").map(transform_tag))

print(dataset.distinct("tags"))
print(view.distinct("tags"))
Parameters
chars:Nonean optional string or ViewExpression resolving to a string expression specifying characters to remove
Returns
a ViewExpression
def second(self): (source)

Returns the second portion of this date expression (in UTC) as a number between 0 and 59.

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 0, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 0, 2),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 0, 3),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1, 0, 0, 4),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the second portion of the dates in the dataset
print(dataset.values(F("created_at").second()))

# Samples with even seconds
view = dataset.match(F("created_at").second() % 2 == 0)
print(len(view))
Returns
a ViewExpression
def set_equals(self, *args): (source)

Checks whether this expression, which must resolve to an array, contains the same distinct values as each of the given array(s) or array expression(s).

The arrays are treated as sets, so all duplicates are ignored.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(
            filepath="image1.jpg",
            tags=["a", "b", "a", "b"],
            other_tags=["a", "b", "b"],
        )
    ]
)

print(dataset.values(F("tags").set_equals(F("other_tags"))))
# [True]
Parameters
*argsone or more arrays or ViewExpression instances that resolve to array expressions
Returns
a ViewExpression
def set_field(self, field, value_or_expr, relative=True): (source)

Sets the specified field or embedded field of this expression, which must resolve to a document, to the given value or expression.

By default, the provided expression is computed by applying it to this expression via self.apply(value_or_expr).

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

#
# Replaces the `label` attributes of the objects in the
# `predictions` field according to the following rule:
#
#   If the `label` starts with `b`, replace it with `b`. Otherwise,
#   replace it with "other"
#
view = dataset.set_field(
    "predictions.detections",
    F("detections").map(
        F().set_field(
            "label",
            F("label").re_match("^b").if_else("b", "other"),
        )
    )
)

print(view.count_values("predictions.detections.label"))
Parameters
fieldthe "field" or "embedded.field.name" to set
value_or_expra literal value or ViewExpression defining the field to set
relative:Truewhether to compute value_or_expr by applying it to this expression (True), or to use it untouched (False)
Returns
a ViewExpression
def sin(self): (source)

Computes the sine of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `sin()`
view = dataset.match(F("uniqueness").sin() >= np.sin(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def sinh(self): (source)

Computes the hyperbolic sine of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `sinh()`
view = dataset.match(F("uniqueness").sinh() >= np.sinh(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def sort(self, key=None, numeric=False, reverse=False): (source)

Sorts this expression, which must resolve to an array.

If no key is provided, this array must contain elements whose BSON representation can be sorted by JavaScript's .sort() method.

If a key is provided, the array must contain documents, which are sorted by key, which must be a field or embedded field.

Examples:

#
# Sort the tags of each sample in a dataset
#

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(filepath="im1.jpg", tags=["z", "f", "p", "a"]),
        fo.Sample(filepath="im2.jpg", tags=["y", "q", "h", "d"]),
        fo.Sample(filepath="im3.jpg", tags=["w", "c", "v", "l"]),
    ]
)

# Sort the `tags` of each sample
view = dataset.set_field("tags", F("tags").sort())

print(view.first().tags)

#
# Sort the predictions in each sample of a dataset by `confidence`
#

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

view = dataset.set_field(
    "predictions.detections",
    F("detections").sort(key="confidence", numeric=True, reverse=True)
)

sample = view.first()
print(sample.predictions.detections[0].confidence)
print(sample.predictions.detections[-1].confidence)
Parameters
key:Nonean optional field or embedded.field.name to sort by
numeric:Falsewhether the array contains numeric values. By default, the values will be sorted alphabetically by their string representations
reverse:Falsewhether to sort in descending order
Returns
a ViewExpression
def split(self, delimiter, maxsplit=None): (source)

Splits this expression, which must resolve to a string, by the given delimiter.

The result is a string array that contains the chunks with the delimiter removed. If the delimiter is not found, this full string is returned as a single element array.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Add "-good" to the first tag and then split on "-" to create two
# tags for each sample
view = dataset.set_field(
    "tags", F("tags")[0].concat("-good").split("-")
)

print(view.first().tags)
Parameters
delimiterthe delimiter string or ViewExpression resolving to a string expression
maxsplit:Nonea maximum number of splits to perform, from the left
Returns
a ViewExpression
def sqrt(self): (source)

Computes the square root of this expression, which must resolve to a numeric value.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Bboxes are in [top-left-x, top-left-y, width, height] format
center_dist = (
    (F("bounding_box")[0] + 0.5 * F("bounding_box")[2] - 0.5) ** 2 +
    (F("bounding_box")[1] + 0.5 * F("bounding_box")[3] - 0.5) ** 2
).sqrt()

# Only contains predictions whose bounding box center is a distance
# of at most 0.02 from the center of the image
view = dataset.select_fields("predictions").filter_labels(
    "predictions", center_dist < 0.02
)

session = fo.launch_app(view=view)
Returns
a ViewExpression
def starts_with(self, str_or_strs, case_sensitive=True): (source)

Determines whether this expression, which must resolve to a string, starts with the given string or string(s).

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose images are in "/Users" or "/home" directories
view = dataset.match(F("filepath").starts_with(("/Users", "/home"))

print(view.count())
print(view.first().filepath)
Parameters
str_or_strsa string or iterable of strings
case_sensitive:Truewhether to perform a case sensitive match
Returns
a ViewExpression
def std(self, sample=False): (source)

Returns the standard deviation of the values in this expression, which must resolve to a numeric array.

Missing or None-valued elements are ignored.

By default, the population standard deviation is returned. If you wish to compute the sample standard deviation instead, set sample=True.

See https://en.wikipedia.org/wiki/Standard_deviation#Estimation for more information on population (biased) vs sample (unbiased) standard deviation.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Add a field to each `predictions` object that records the
# standard deviation of the confidences
view = dataset.set_field(
    "predictions.conf_std",
    F("detections").map(F("confidence")).std()
)

print(view.bounds("predictions.conf_std"))
Parameters
sample:Falsewhether to compute the sample standard deviation rather than the population standard deviation
Returns
a ViewExpression
def strip(self, chars=None): (source)

Removes whitespace characters from the beginning and end of this expression, which must resolve to a string.

If chars is provided, those characters are removed instead of whitespace.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewExpression as E
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Adds and then strips whitespace from each tag
transform_tag = E(" ").concat(F(), " ").rstrip()
view = dataset.set_field("tags", F("tags").map(transform_tag))

print(dataset.distinct("tags"))
print(view.distinct("tags"))
Parameters
chars:Nonean optional string or ViewExpression resolving to a string expression specifying characters to remove
Returns
a ViewExpression
def strlen(self): (source)

Computes the length of this expression, which must resolve to a string.

If this expression's value is null or missing, zero is returned.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Records the length of each predicted object's `label`
label_len = F().set_field("label_len", F("label").strlen())
view = dataset.set_field(
    "predictions.detections",
    F("detections").map(label_len),
)

print(view.bounds("predictions.detections.label_len"))
Returns
a ViewExpression
def substr(self, start=None, end=None, count=None): (source)

Extracts the specified substring from this expression, which must resolve to a string.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Truncate the `label` of each prediction to 3 characters
truncate_label = F().set_field("label", F("label").substr(count=3))
view = dataset.set_field(
    "predictions.detections",
    F("detections").map(truncate_label),
)

print(view.distinct("predictions.detections.label"))
Parameters
start:Nonethe starting index of the substring. If negative, specifies an offset from the end of the string
end:Nonethe ending index of the substring. If negative, specifies an offset from the end of the string
count:Nonethe substring length to extract. If None, the rest of the string is returned
Returns
a ViewExpression
def sum(self): (source)

Returns the sum of the values in this expression, which must resolve to a numeric array.

Missing, non-numeric, or None-valued elements are ignored.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Add a field to each `predictions` object that records the total
# confidence of the predictions
view = dataset.set_field(
    "predictions.total_conf",
    F("detections").map(F("confidence")).sum()
)

print(view.bounds("predictions.total_conf"))
Returns
a ViewExpression
def switch(self, mapping, default=None): (source)

Applies a switch statement to this expression, which effectively computes the given pseudocode:

for key, value in mapping.items():
    if self.apply(key):
        return value

if default is not None:
    return default

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Round `uniqueness` values to either 0.25 or 0.75
view = dataset.set_field(
    "uniqueness",
    F("uniqueness").switch(
        {
            (0.0 < F()) & (F() <= 0.5): 0.25,
            (0.5 < F()) & (F() <= 1.0): 0.75,
        },
    )
)

print(view.count_values("uniqueness"))
Parameters
mappinga dict mapping boolean ViewExpression keys to literal or ViewExpression values
default:Nonean optional literal or ViewExpression to return if none of the switch branches are taken
Returns
a ViewExpression
def tan(self): (source)

Computes the tangent of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `tan()`
view = dataset.match(F("uniqueness").tan() >= np.tan(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def tanh(self): (source)

Computes the hyperbolic tangent of this expression, which must resolve to a numeric value, in radians.

Examples:

import numpy as np

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Get samples whose `uniqueness` value is >= 0.5 using `tanh()`
view = dataset.match(F("uniqueness").tanh() >= np.tanh(0.5))

print(view.bounds("uniqueness"))
Returns
a ViewExpression
def to_bool(self): (source)

Converts the expression to a boolean value.

See this page for conversion rules.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart").clone()

# Adds a `uniqueness_bool` field that is False when
# `uniqueness < 0.5` and True when `uniqueness >= 0.5`
dataset.add_sample_field("uniqueness_bool", fo.BooleanField)
view = dataset.set_field(
    "uniqueness_bool", (2.0 * F("uniqueness")).floor().to_bool()
)

print(view.count_values("uniqueness_bool"))
Returns
a ViewExpression
def to_date(self): (source)

Converts the expression to a date value.

See this page for conversion rules.

Examples:

from datetime import datetime
import pytz

import fiftyone as fo
from fiftyone import ViewField as F

now = datetime.utcnow().replace(tzinfo=pytz.utc)

sample = fo.Sample(
    filepath="image.png",
    date_ms=1000 * now.timestamp(),
    date_str=now.isoformat(),
)

dataset = fo.Dataset()
dataset.add_sample(sample)

# Convert string/millisecond representations into datetimes
dataset.add_sample_field("date1", fo.DateTimeField)
dataset.add_sample_field("date2", fo.DateTimeField)
(
    dataset
    .set_field("date1", F("date_ms").to_date())
    .set_field("date2", F("date_str").to_date())
    .save()
)

print(dataset.first())
Returns
a ViewExpression
def to_double(self): (source)

Converts the expression to a double precision value.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart").clone()

# Adds a `uniqueness_float` field that is 0.0 when
# `uniqueness < 0.5` and 1.0 when `uniqueness >= 0.5`
dataset.add_sample_field("uniqueness_float", fo.FloatField)
view = dataset.set_field(
    "uniqueness_float", (F("uniqueness") >= 0.5).to_double()
)

print(view.count_values("uniqueness_float"))

See this page for conversion rules.

Returns
a ViewExpression
def to_int(self): (source)

Converts the expression to an integer value.

See this page for conversion rules.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart").clone()

# Adds a `uniqueness_int` field that contains the value of the
# first decimal point of the `uniqueness` field
dataset.add_sample_field("uniqueness_int", fo.IntField)
view = dataset.set_field(
    "uniqueness_int", (10.0 * F("uniqueness")).floor().to_int()
)

print(view.count_values("uniqueness_int"))
Returns
a ViewExpression
def to_mongo(self, prefix=None): (source)

Returns a MongoDB representation of the expression.

Parameters
prefix:Nonean optional prefix to prepend to all ViewField instances in the expression
Returns
a MongoDB expression
def to_string(self): (source)

Converts the expression to a string value.

See this page for conversion rules.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart").clone()

# Adds a `uniqueness_str` field that is "true" when
# `uniqueness >= 0.5` and "false" when `uniqueness < 0.5`
dataset.add_sample_field("uniqueness_str", fo.StringField)
view = dataset.set_field(
    "uniqueness_str", (F("uniqueness") >= 0.5).to_string()
)

print(view.count_values("uniqueness_str"))
Returns
a ViewExpression
def trunc(self, place=0): (source)

Truncates this expression, which must resolve to a numeric value, at the specified decimal place.

Positive values of place will truncate to place decimal places:

place=2: 1234.5678 --> 1234.56

Negative values of place will replace place digits left of the decimal with zero:

place=-1: 1234.5678 --> 1230

Examples:

import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")
dataset.compute_metadata()

# Only contains samples whose height is in [500, 600) pixels
view = dataset.match(F("metadata.height").trunc(-2) == 500)

print(view.bounds("metadata.height"))
Parameters
place:0the decimal place at which to truncate
Returns
a ViewExpression
def type(self): (source)

Returns the type string of this expression.

See this page for more details.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Set `uniqueness` values below 0.75 to None
view = dataset.set_field(
    "uniqueness",
    (F("uniqueness") > 0.75).if_else(F("uniqueness"), None)
)

# Create a view that only contains samples with non-None uniqueness
unique_only_view = view.match(F("uniqueness").type() != "null")

print(len(unique_only_view))
Returns
a ViewExpression
def union(self, *args): (source)

Computes the set union of this expression, which must resolve to an array, and the given array(s) or array expression(s).

The arrays are treated as sets, so all duplicates are removed.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(
            filepath="image1.jpg",
            tags=["a", "b"],
            other_tags=["a", "c"]
        )
    ]
)

print(dataset.values(F("tags").union(F("other_tags"))))
# [['a', 'b', 'c']]
Parameters
*argsone or more arrays or ViewExpression instances that resolve to array expressions
Returns
a ViewExpression
def unique(self): (source)

Returns an array containing the unique values in this expression, which must resolve to an array.

Examples:

import fiftyone as fo
from fiftyone import ViewField as F

dataset = fo.Dataset()
dataset.add_samples(
    [
        fo.Sample(
            filepath="image1.jpg",
            tags=["a", "b", "a", "b"],
        )
    ]
)

print(dataset.values(F("tags").unique()))
# [['a', 'b']]
Returns
a ViewExpression
def upper(self): (source)

Converts this expression, which must resolve to a string, to uppercase.

Examples:

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset("quickstart")

# Converts all tags to uppercase
transform_tag = F().upper()
view = dataset.set_field("tags", F("tags").map(transform_tag))

print(dataset.distinct("tags"))
print(view.distinct("tags"))
Returns
a ViewExpression
def week(self): (source)

Returns the week of the year of this date expression (in UTC) as a number between 0 and 53.

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 2, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 3, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 4, 1),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the weeks of the year for the dataset
print(dataset.values(F("created_at").week()))

# Samples with even months of the week
view = dataset.match(F("created_at").week() % 2 == 0)
print(len(view))
Returns
a ViewExpression
def year(self): (source)

Returns the year of this date expression (in UTC).

Examples:

from datetime import datetime

import fiftyone as fo
from fiftyone import ViewField as F

samples = [
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1970, 1, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1971, 1, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1972, 1, 1),
    ),
    fo.Sample(
        filepath="image1.jpg",
        created_at=datetime(1973, 1, 1),
    ),
]

dataset = fo.Dataset()
dataset.add_samples(samples)

# Get the years for the dataset
print(dataset.values(F("created_at").year()))

# Samples from even years
view = dataset.match(F("created_at").year() % 2 == 0)
print(len(view))
Returns
a ViewExpression

Whether this expression's prefix is frozen.

def _freeze_prefix(self, prefix): (source)

Undocumented

def _function(self, function): (source)

Undocumented

def _let_in(self, expr, var='expr'): (source)

Undocumented

Undocumented

Undocumented