Combining arrays

Import the LArray library:


In [ ]:
from larray import *

In [ ]:
# load the 'demography_eurostat' dataset
demography_eurostat = load_example_data('demography_eurostat')

# load 'gender' and 'time' axes
gender = demography_eurostat.gender
time = demography_eurostat.time

In [ ]:
# load the 'population' array from the 'demography_eurostat' dataset
population = demography_eurostat.population

# show 'population' array 
population

In [ ]:
# load the 'population_benelux' array from the 'demography_eurostat' dataset
population_benelux = demography_eurostat.population_benelux

# show 'population_benelux' array 
population_benelux

The LArray library offers several methods and functions to combine arrays:

  • insert: inserts an array in another array along an axis
  • append: adds an array at the end of an axis.
  • prepend: adds an array at the beginning of an axis.
  • extend: extends an array along an axis.
  • stack: combines several arrays along a new axis.

Insert


In [ ]:
other_countries = zeros((Axis('country=Luxembourg,Netherlands'), gender, time), dtype=int)

# insert new countries before 'France'
population_new_countries = population.insert(other_countries, before='France')
population_new_countries

See insert for more details and examples.

Append

Append one element to an axis of an array:


In [ ]:
# append data for 'Luxembourg'
population_new = population.append('country', population_benelux['Luxembourg'], 'Luxembourg')
population_new

The value being appended can have missing (or even extra) axes as long as common axes are compatible:


In [ ]:
population_lux = Array([-1, 1], gender)
population_lux

In [ ]:
population_new = population.append('country', population_lux, 'Luxembourg')
population_new

See append for more details and examples.

Prepend

Prepend one element to an axis of an array:


In [ ]:
# append data for 'Luxembourg'
population_new = population.prepend('country', population_benelux['Luxembourg'], 'Luxembourg')
population_new

See prepend for more details and examples.

Extend

Extend an array along an axis with another array with that axis (but other labels)


In [ ]:
population_extended = population.extend('country', population_benelux[['Luxembourg', 'Netherlands']])
population_extended

See extend for more details and examples.

Stack

Stack several arrays together to create an entirely new dimension


In [ ]:
# imagine you have loaded data for each country in different arrays 
# (e.g. loaded from different Excel sheets)
population_be = population['Belgium']
population_fr = population['France']
population_de = population['Germany']

population_stacked = stack({'Belgium': population_be, 'France': population_fr, 'Germany': population_de}, 'country')
population_stacked

See stack for more details and examples.