The neural code that relates the firing of neurons to the generation of behavior and mental states must be implemented by spatiotemporal patterns of activity across neuronal populations. These patterns engage selective groups of neurons, called neuronal ensembles, which are emergent building blocks of neural circuits. We review optical and computational methods, based on two-photon calcium imaging and two-photon optogenetics, to detect, characterize, and manipulate neuronal ensembles in three dimensions. We review data using these methods in the mammalian cortex that demonstrate the existence of neuronal ensembles in the spontaneous and evoked cortical activity in vitro and in vivo. Moreover, two-photon optogenetics enable the possibility of artificially imprinting neuronal ensembles into awake, behaving animals and of later recalling those ensembles selectively by stimulating individual cells. These methods could enable deciphering the neural code and also be used to understand the pathophysiology of and design novel therapies for neurological and mental diseases.