More Value Expressions

Setup

In [1]:
import ibis
import os
hdfs_port = os.environ.get('IBIS_WEBHDFS_PORT', 50070)
hdfs = ibis.hdfs_connect(host='quickstart.cloudera', port=hdfs_port)
con = ibis.impala.connect(host='quickstart.cloudera', database='ibis_testing',
                          hdfs_client=hdfs)
ibis.options.interactive = True

Type casting

The Ibis type system is pretty basic and will get better (and more documented over time). It maps directly onto the current Impala type system

  • int8
  • int16
  • int32
  • int64
  • boolean
  • float
  • double
  • string
  • timestamp
  • decimal($precision, $scale)

These type names can be used to cast from one type to another

In [2]:
table = con.table('functional_alltypes')
table.string_col.cast('double').sum()
Out[2]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_4_0.png
In [3]:
table.string_col.cast('decimal(12,2)').sum()
Out[3]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_5_0.png

Case / if-then-else expressions

We support a number of variants of the SQL-equivalent CASE expression, and will add more API functions over time to meet different use cases and enhance the expressiveness of any branching-based value logic.

In [4]:
expr = (table.string_col
        .case()
        .when('4', 'fee')
        .when('7', 'fi')
        .when('1', 'fo')
        .when('0', 'fum')
        .else_(table.string_col)
        .end()
        .name('new_strings'))

expr.value_counts()
Out[4]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_7_0.png

If the else_ default condition is not provided, any values not matching one of the conditions will be NULL.

In [5]:
expr = (table.string_col
        .case()
        .when('4', 'fee')
        .when('7', 'fi')
        .end()
        .name('with_nulls'))

expr.value_counts()
Out[5]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_9_0.png

To test for an arbitrary series of boolean conditions, use the case API method and pass any boolean expressions potentially involving columns of the table:

In [6]:
expr = (ibis.case()
        .when(table.int_col > 5, table.bigint_col * 2)
        .when(table.int_col > 2, table.bigint_col)
        .else_(table.int_col)
        .end())

table['id', 'int_col', 'bigint_col', expr.name('case_result')].limit(20)
Out[6]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_11_0.png

Simple ternary-cases (like the Python X if COND else Y) can be written using the ifelse function:

In [7]:
expr = ((table.int_col > 5)
        .ifelse(table.bigint_col / 2, table.bigint_col * 2)
        .name('ifelse_result'))

table['int_col', 'bigint_col', expr].limit(10)
Out[7]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_13_0.png

Set membership

The isin and notin functions are like their pandas counterparts. These can take:

  • A list of value expressions, either literal values or other column expressions
  • An array/column expression of some kind
In [8]:
bool_clause = table.string_col.notin(['1', '4', '7'])
table[bool_clause].string_col.value_counts()
Out[8]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_15_0.png

You can also check for membership in an array. Here is an example of filtering based on the top 3 (ignoring ties) most frequently-occurring values in the string_col column of alltypes:

In [9]:
top_strings = table.string_col.value_counts().limit(3).string_col
top_filter = table.string_col.isin(top_strings)
expr = table[top_filter]

expr.count()
Out[9]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_17_0.png

This is a common enough operation that we provide a special analytical filter function topk:

In [10]:
table[table.string_col.topk(3)].count()
Out[10]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_19_0.png

Cool, huh? More on topk later.

Null-ness

Like their pandas equivalents, the isnull and notnull functions return True values if the values are null, or non-null, respectively. For example:

In [11]:
expr = (table.string_col
        .case()
        .when('4', 'fee')
        .when('7', 'fi')
        .when('1', 'fo')
        .end()
        .name('new_strings'))

expr.isnull().value_counts()
Out[11]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_22_0.png

Functions like isnull can be combined with case expressions or functions like ifelse to replace null values with some other value. ifelse here will use the first value supplied for any True value and the second value for any False value. Either value can be a scalar or array.

In [12]:
expr2 = expr.isnull().ifelse('was null', expr).name('strings')
expr2.value_counts()
Out[12]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_24_0.png

Distinct-based operations

Ibis supports using distinct to remove duplicate rows or values on tables or arrays. For example:

In [13]:
table['int_col', 'bigint_col'].distinct()
Out[13]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_26_0.png
In [14]:
table.string_col.distinct()
Out[14]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_27_0.png

This can be combined with count to form a reduction metric:

In [15]:
metric = (table.bigint_col
          .distinct().count()
          .name('unique_bigints'))

This is common enough to have a shortcut nunique:

In [16]:
table.string_col.nunique()
Out[16]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_31_0.png

String operations

What’s supported is pretty basic right now. We intend to support the full gamut of regular expression munging with a nice API, though in some cases some work will be required on Impala’s backend to support everything.

In [17]:
nation = con.table('tpch_nation')
nation.limit(5)
Out[17]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_33_0.png

At the moment, basic substring operations (substr, with conveniences left and right) and Python-like APIs such as lower and upper (for case normalization) are supported. So you could count first letter occurrences in a string column like so:

In [18]:
expr = nation.n_name.lower().left(1).name('first_letter')
expr.value_counts().sort_by(('count', False))
Out[18]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_35_0.png

For fuzzy and regex filtering/searching, you can use one of the following

  • like, works as the SQL LIKE keyword
  • rlike, like re.search or SQL RLIKE
  • contains, like x in str_value in Python
In [19]:
nation[nation.n_name.like('%GE%')]
Out[19]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_37_0.png
In [20]:
nation[nation.n_name.lower().rlike('.*ge.*')]
Out[20]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_38_0.png
In [21]:
nation[nation.n_name.lower().contains('ge')]
Out[21]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_39_0.png

Timestamp operations

Date and time functionality is relatively limited at present compared with pandas, but we’ll get there. The main things we have right now are

  • Field access (year, month, day, …)
  • Timedeltas
  • Comparisons with fixed timestamps
In [22]:
table = con.table('functional_alltypes')

table[table.timestamp_col, table.timestamp_col.minute().name('minute')].limit(10)
Out[22]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_41_0.png

Somewhat more comprehensively

In [23]:
def get_field(f):
    return getattr(table.timestamp_col, f)().name(f)

fields = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond']
projection = [table.timestamp_col] + [get_field(x) for x in fields]
table[projection].limit(10)
Out[23]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_43_0.png

For timestamp arithmetic and comparisons, check out functions in the top level ibis namespace. This include things like day and second, but also the ibis.timestamp function:

In [24]:
table[table.timestamp_col.min(), table.timestamp_col.max(), table.count().name('nrows')]
Out[24]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_45_0.png
In [25]:
table[table.timestamp_col < '2010-01-01'].count()
Out[25]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_46_0.png
In [26]:
table[table.timestamp_col <
      (ibis.timestamp('2010-01-01') + ibis.month(3))].count()
Out[26]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_47_0.png
In [27]:
expr = (table.timestamp_col + ibis.day(1) + ibis.hour(4)).name('offset')
table[table.timestamp_col, expr, ibis.now().name('current_time')].limit(10)
Out[27]:
../../_images/notebooks_tutorial_4-More-Value-Expressions_48_0.png