logic_parser#
- gammapy.utils.scripts.logic_parser(table, expression)[source]#
Parse and apply a logical expression to filter rows from an Astropy Table.
This function evaluates a logical expression on each row of the input table and returns a new table containing only the rows that satisfy the expression. The expression can reference any column in the table by name and supports logical operators (
and,or), comparison operators (<,<=,>,>=,==,!=,in), lists, constants, and chained comparisons (e.g.1 < OBS_ID < 3).Chained comparisons follow standard Python semantics and are equivalent to combining individual comparisons with
and. For example,1 < OBS_ID < 3is equivalent to(OBS_ID > 1) and (OBS_ID < 3).- Parameters:
- table
Table The input table to filter.
- expressionstr
The logical expression to evaluate on each row. The expression can reference any column in the table by name.
- table
- Returns:
- table
Table A table view containing only the rows that satisfy the expression. If no rows match the condition, an empty table with the same column names and data types as the input table is returned.
- table
Examples
Given a table with columns ‘OBS_ID’ and ‘EVENT_TYPE’:
>>> from astropy.table import Table >>> data = {'OBS_ID': [1, 2, 3, 4], 'EVENT_TYPE': ['1', '3', '4', '2']} >>> table = Table(data)
Standard logical expression:
>>> expression = '(OBS_ID < 3) and (OBS_ID > 1)' >>> logic_parser(table, expression)
Using chained comparisons:
>>> expression = '1 < OBS_ID < 3' >>> logic_parser(table, expression)
Combining chained comparisons with other conditions:
>>> expression = '(1 < OBS_ID < 4) and (EVENT_TYPE in ["3", "4"])' >>> logic_parser(table, expression)