{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Indexing, Selecting and Assigning\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Import the LArray library:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from larray import *" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Import the test array ``population``:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# let's start with\n", "population = load_example_data('demography_eurostat').population\n", "population" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Selecting (Subsets)\n", "\n", "The ``Array`` class allows to select a subset either by labels or indices (positions)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Selecting by Labels\n", "\n", "To take a subset of an array using labels, use brackets [ ].\n", "\n", "Let's start by selecting a single element:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "population['Belgium', 'Female', 2017]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As long as there is no ambiguity (i.e. axes sharing one or several same label(s)), the order of indexing does not matter. \n", "So you usually do not care/have to remember about axes positions during computation. It only matters for output." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# order of index doesn't matter\n", "population['Female', 2017, 'Belgium']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Selecting a subset is done by using slices or lists of labels:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "population[['Belgium', 'Germany'], 2014:2016]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Slices bounds are optional:\n", "if not given, start is assumed to be the first label and stop is the last one." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# select all years starting from 2015\n", "population[2015:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# select all first years until 2015\n", "population[:2015]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Slices can also have a step (defaults to 1), to take every Nth labels:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# select all even years starting from 2014\n", "population[2014::2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "