This is the second introductory tutorial to Ibis. If you are new to Ibis, you may want to start at the beginning of this tutorial.
In the first notebook we saw how to load and query data using
ibis. In this notebook we'll continue with the same dataset, building up some more complicated queries.
from tutorial_utils import setup setup()
import ibis ibis.options.interactive = True connection = ibis.sqlite.connect("geography.db") countries = connection.table("countries") countries["name", "continent", "area_km2", "population"]
We will continue by exploring the data by continent. We will start by creating an expression with the continent names, since our table only contains the abbreviations.
An expression is one or more operations performed over the data. They can be used to retrieve the data or to build more complex operations.
In this case we will use a
case conditional statement to replace values depending on a condition.
case expression will return a case builder, and must be followed by one or more
else_ call, and must end with a call to
end, to complete the full expression.
The expression where
case is called (
countries['continent'] in this case)
is evaluated to see if it's equal to any of the first arguments of the calls to
when. And the second
argument is returned. If the value does not match any of the
when values, the value of
else_ is returned.
continent_name = ( countries["continent"] .case() .when("NA", "North America") .when("SA", "South America") .when("EU", "Europe") .when("AF", "Africa") .when("AS", "Asia") .when("OC", "Oceania") .when("AN", "Antarctica") .else_("Unknown continent") .end() .name("continent_name") ) continent_name
What we did is take the values of the column
countries['continent'], and we created a calculated
column with the names of the continents, as defined in the
This calculated column is an expression. The computations didn't happen when defining the
variable, and the results are not stored. They have been computed when we printed its content.
We can see that by checking the type of
In the next tutorial we will see more about eager and lazy mode, and when operations are being executed. For now we can think that the query to the database happens only when we want to see the results.
The important part is that now we can use our
continent_name expression in other expressions.
For example, since this is a column (a
StringColumn to be specific), we can use it as a column
to query the countries table.
Note that when we created the expression we added
.name('continent_name') to it, so the column
has a name when being returned.
countries["name", continent_name, "area_km2", "population"]
Just for illustration, let's repeat the same query, but renaming the expression to
when using it in the list of columns to fetch.
countries["name", continent_name.name("continent"), "area_km2", "population"]
Now, let's group our data by continent, and let's find the total population of each.
countries.group_by(continent_name).aggregate( countries["population"].sum().name("total_population") )
We can see how Asia is the most populated country, followed by Africa. Antarctica is the least populated, as we would expect.
The code to aggregate has two main parts:
group_bymethod, that receive the column, expression or list of them to group by
aggregatemethod, that receives an expression with the reduction we want to apply
To make things a bit clearer, let's first save the reduction.
total_population = countries["population"].sum().name("total_population") total_population
As we can see, if we perform the operation directly, we will get the sum of the total in the column.
But if we take the
total_population expression as the parameter of the
aggregate method, then the total is computed
over every group defined by the
If we want to compute two aggregates at the same time, we can pass a list to the
For illustration, we use the
continent column, instead of the
continent_names expression. We can
use both column names and expressions, and also a list with any of them (e.g.
countries.group_by("continent").aggregate( [total_population, countries["area_km2"].mean().name("average_area")] )
Now we are going to get the total gross domestic product (GDP) for each continent. In this case, the GDP data
is not in the same table
countries, but in a table
gdp = connection.table("gdp") gdp
The table contains information for different years, we can easily check the range with:
Now, we are going to join this data with the
countries table so we can obtain the continent
of each country. The
countries table has several different codes for the countries. Let's find out which
one matches the three letter code in the
countries["iso_alpha2", "iso_alpha3", "iso_numeric", "fips", "name"]
gdp corresponds to
iso_alpha3 in the
countries table. We can also see
gdp table has
10,000 rows, while
252. We will start joining the
two tables by the codes that match, discarding the codes that do not exist in both tables.
This is called an inner join.
countries_and_gdp = countries.inner_join( gdp, predicates=countries["iso_alpha3"] == gdp["country_code"] ) countries_and_gdp[countries, gdp]
We joined the table with the information for all years. Now we are going to just take the information about the last available year, 2017.
gdp_2017 = gdp.filter(gdp["year"] == 2017) gdp_2017
Joining with the new expression we get:
countries_and_gdp = countries.inner_join( gdp_2017, predicates=countries["iso_alpha3"] == gdp_2017["country_code"] ) countries_and_gdp[countries, gdp_2017]
We have called the
inner_join method of the
countries table and passed
gdp table as a parameter. The method receives a second parameter,
predicates, that is used to specify
how the join will be performed. In this case we want the
iso_alpha3 column in
country_code column in
gdp. This is specified with the expression
countries['iso_alpha3'] == gdp['country_code'].