Skip to content

Indexing K Objects

Indexing in q works differently than you may be used to, and that behaviour largely carries over into PyKX for indexing K objects. For more information about how indexing in q works (and by extension, how indexing K objects in PyKX work), refer to the following sections of the q tutorial book Q For Mortals:

Indexes used on K objects in PyKX are converted to equivalent K objects in q using the toq module, just like any other Python to q conversion. To guarantee that the index used against a K object is what you intend it to be, you may perform the conversion of the index yourself before applying it. When K objects are used as the index for another K object, the index object is applied to the pykx.Collection object as they would be in q; i.e. as described in Q For Mortals.

The only exception to this is in how we handle indexes which are out of bounds, or do not match any key. In PyKX, these cases result in an IndexError or KeyError being raised. To work around this and get the exact same behaviour as q, you can apply the index to the collection manually like so:

q('@', collection, index)

To perform indexing into data obtained from q via PyKX in a Numpy or Pandas style, you should convert the K object to a Numpy or Pandas object using the built-in conversion methods such as .np() or .pd().