MENU

New Introduction to the data_algebra

This article was first published on python – Win-Vector Blog , and kindly contributed to python-bloggers. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

We’ve had really good progress in bringing the

Python
data_algebra
data_algebra
to feature parity with
R
R
rquery
rquery
. In fact we are able to reproduced the New Introduction to
rquery
rquery article
as a “New Introduction to the
data_algebra
data_algebra” here.

The idea is: you may have good reasons to want to work in

R
R or to want to work in
Python
Python. And Win-Vector LLC wants to leave the choice of
R
R versus
Python
Python to you, by providing equivalent strong tools for each platform.

In the article below notice we can explore the same concepts in

R
R or in
Python
Python (with a different syntax emphasizing quotation and method-chaining, to be more natively “Pythonic”).

Introduction to the
data_algebra
data_algebra

The

data_algebra is a data wrangling system designed to express complex data manipulation as a series of simple data transforms. This is in the spirit of
R
R‘s
base::transform()
base::transform(),
dplyr
dplyr‘s
dplyr::mutate()
dplyr::mutate(), or
rquery
rquery
‘s
rquery::extend()
rquery::extend() and uses a method chaining notation. The operators themselves follow the selections in Codd’s relational algebra, with the addition of the traditional
SQL
SQL “window functions.” More on the background and context of
data_algebra
data_algebra can be found here.

The

Python
Python/
data_algebra
data_algebra version of this introduction is here, and the
R
R/
rquery
rquery version of this introduction is here.

In transform formulations data manipulation is written as transformations that produce new

DataFrame
DataFrames, instead of as alterations of a primary data structure (as is the case with
data.table
data.table). Transform system can use more space and time than in-place methods. However, in our opinion, transform systems have a number of pedagogical advantages.

In

data_algebra
data_algebra‘s case the primary set of data operators is as follows:

  • drop_columns
    drop_columns
  • select_columns
    select_columns
  • rename_columns
    rename_columns
  • select_rows
    select_rows
  • order_rows
    order_rows
  • extend
    extend
  • project
    project
  • natural_join
    natural_join
  • convert_records
    convert_records.

These operations break into a small number of themes:

  • Simple column operations (selecting and re-naming columns).
  • Simple row operations (selecting and re-ordering rows).
  • Creating new columns or replacing columns with new calculated values.
  • Aggregating or summarizing data.
  • Combining results between two
    DataFrame
    DataFrames.
  • General conversion of record layouts.

The point is: Codd worked out that a great number of data transformations can be decomposed into a small number of the above steps.

data_algebra
data_algebra supplies a high performance implementation of these methods that scales from in-memory scale up through big data scale (to just about anything that supplies a sufficiently powerful
SQL
SQL interface, such as PostgreSQL, Apache Spark, or Google BigQuery).

We will work through simple examples/demonstrations of the

data_algebra
data_algebra data manipulation operators.

data_algebra
data_algebra operators

Simple column operations (selecting and re-naming columns)

The simple column operations are as follows.

  • drop_columns
    drop_columns
  • select_columns
    select_columns
  • rename_columns
    rename_columns

These operations are easy to demonstrate.

We set up some simple data.

In [1]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import pandas
d = pandas.DataFrame({
'x': [1, 1, 2],
'y': [5, 4, 3],
'z': [6, 7, 8],
})
d
import pandas d = pandas.DataFrame({ 'x': [1, 1, 2], 'y': [5, 4, 3], 'z': [6, 7, 8], }) d
import pandas

d = pandas.DataFrame({
  'x': [1, 1, 2],
  'y': [5, 4, 3],
  'z': [6, 7, 8],
})

d
Out[1]:
xyz
0156
1147
2238
For example:
drop_columns
drop_columns works as follows.
drop_columns
drop_columns creates a new
DataFrame
DataFrame without certain columns. We can start by wrapping our
DataFrame
DataFrame
d
d for processing, then applying the
drop_columns()
drop_columns() operators, and finally ending and executing the chain with the
ex()
ex() method.

In [2]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from data_algebra.data_ops import *
wrap(d). \
drop_columns(['y', 'z']). \
ex()
from data_algebra.data_ops import * wrap(d). \ drop_columns(['y', 'z']). \ ex()
from data_algebra.data_ops import *

wrap(d). \
    drop_columns(['y', 'z']). \
    ex()
Out[2]:
x
01
11
22
In all cases the first argument of a
data_algebra
data_algebra operator is either the data to be processed, or an earlier
data_algebra
data_algebra pipeline to be extended. We will take about composing
data_algebra
data_algebra operations after we work through examples of all of the basic operations.

select_columns
select_columns‘s action is also obvious from example.

In [3]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrap(d). \
select_columns(['x', 'y']). \
ex()
wrap(d). \ select_columns(['x', 'y']). \ ex()
wrap(d). \
  select_columns(['x', 'y']). \
  ex()
Out[3]:
xy
015
114
223
rename_columns
rename_columns is given as name-assignments of the form
'new_name': 'old_name'
'new_name': 'old_name':

In [4]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrap(d). \
rename_columns({
'x_new_name': 'x',
'y_new_name': 'y'
}). \
ex()
wrap(d). \ rename_columns({ 'x_new_name': 'x', 'y_new_name': 'y' }). \ ex()
wrap(d). \
  rename_columns({
     'x_new_name': 'x',
     'y_new_name': 'y'
    }). \
  ex()
Out[4]:
x_new_namey_new_namez
0156
1147
2238

Simple row operations (selecting and re-ordering rows)

The simple row operations are:

  • select_rows
    select_rows
  • order_rows
    order_rows

select_rows
select_rows keeps the set of rows that meet a given predicate expression.

In [5]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrap(d). \
select_rows('x == 1'). \
ex()
wrap(d). \ select_rows('x == 1'). \ ex()
wrap(d). \
  select_rows('x == 1'). \
  ex()
Out[5]:
xyz
0156
1147
order_rows
order_rows re-orders rows by a selection of column names (and allows reverse ordering by naming which columns to reverse in the optional
reverse
reverse argument). Multiple columns can be selected in the order, each column breaking ties in the earlier comparisons.

In [6]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrap(d). \
order_rows(
['x', 'y'],
reverse = ['x']). \
ex()
wrap(d). \ order_rows( ['x', 'y'], reverse = ['x']). \ ex()
wrap(d). \
  order_rows(
             ['x', 'y'],
             reverse = ['x']). \
  ex()
Out[6]:
xyz
0238
1147
2156
General
data_algebra
data_algebra operations do not depend on row-order and are not guaranteed to preserve row-order, so if you do want to order rows you should make it the last step of your pipeline.

Creating new columns or replacing columns with new calculated values

The important create or replace column operation is:

  • extend
    extend

extend
extend accepts arbitrary expressions to create new columns (or replace existing ones). For example:

In [7]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrap(d). \
extend({'zzz': 'y / x'}). \
ex()
wrap(d). \ extend({'zzz': 'y / x'}). \ ex()
wrap(d). \
  extend({'zzz': 'y / x'}). \
  ex()
Out[7]:
xyzzzz
01565.0
11474.0
22381.5
We can use
=
= or
:=
:= for column assignment. In these examples we will use
:=
:= to keep column assignment clearly distinguishable from argument binding.

extend
extend allows for very powerful per-group operations akin to what
SQL
SQL
calls “window functions”. When the optional
partitionby
partitionby argument is set to a vector of column names then aggregate calculations can be performed per-group. For example.

In [8]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrap(d). \
extend({
'max_y': 'y.max()',
'shift_z': 'z.shift()',
'row_number': '_row_number()',
'cumsum_z': 'z.cumsum()',},
partition_by = 'x',
order_by = ['y', 'z']). \
ex()
wrap(d). \ extend({ 'max_y': 'y.max()', 'shift_z': 'z.shift()', 'row_number': '_row_number()', 'cumsum_z': 'z.cumsum()',}, partition_by = 'x', order_by = ['y', 'z']). \ ex()
wrap(d). \
  extend({
         'max_y': 'y.max()',
         'shift_z': 'z.shift()',
         'row_number': '_row_number()',
         'cumsum_z': 'z.cumsum()',},
         partition_by = 'x',
         order_by = ['y', 'z']). \
  ex()
Out[8]:
xyzmax_yshift_zrow_numbercumsum_z
015657.0213
11475NaN17
22383NaN18
Notice the aggregates were performed per-partition (a set of rows with matching partition key values, specified by
partitionby
partitionby) and in the order determined by the
orderby
orderby argument (without the
orderby
orderby argument order is not guaranteed, so always set
orderby
orderby for windowed operations that depend on row order!).

More on the window functions can be found here.

Aggregating or summarizing data

The main aggregation method for

data_algebra
data_algebra is:

  • project
    project

project
project performs per-group calculations, and returns only the grouping columns (specified by
groupby
groupby) and derived aggregates. For example:

In [9]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrap(d). \
project({
'max_y': 'y.max()',
'count': '_size()',},
group_by = ['x']). \
ex()
wrap(d). \ project({ 'max_y': 'y.max()', 'count': '_size()',}, group_by = ['x']). \ ex()
wrap(d). \
  project({
         'max_y': 'y.max()',
         'count': '_size()',},
         group_by = ['x']). \
  ex()
Out[9]:
xmax_ycount
0152
1231
Notice we only get one row for each unique combination of the grouping variables. We can also aggregate into a single row by not specifying any
groupby
groupby columns.

In [10]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrap(d). \
project({
'max_y': 'y.max()',
'count': '_size()',
}). \
ex()
wrap(d). \ project({ 'max_y': 'y.max()', 'count': '_size()', }). \ ex()
wrap(d). \
  project({
         'max_y': 'y.max()',
         'count': '_size()',
          }). \
  ex()
Out[10]:
max_ycount
053

Combining results between two
DataFrame
DataFrames

To combine multiple tables in

data_algebra
data_algebra one uses what we call the
natural_join
natural_join operator. In the
data_algebra
data_algebra
natural_join
natural_join, rows are matched by column keys and any two columns with the same name are coalesced (meaning the first table with a non-missing values supplies the answer). This is easiest to demonstrate with an example.

Let’s set up new example tables.

In [11]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
d_left = pandas.DataFrame({
'k': ['a', 'a', 'b'],
'x': [1, None, 3],
'y': [1, None, None],
})
d_left
d_left = pandas.DataFrame({ 'k': ['a', 'a', 'b'], 'x': [1, None, 3], 'y': [1, None, None], }) d_left
d_left = pandas.DataFrame({
  'k': ['a', 'a', 'b'],
  'x': [1, None, 3],
  'y': [1, None, None],
})

d_left
Out[11]:
kxy
0a1.01.0
1aNaNNaN
2b3.0NaN
In [12]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
d_right = pandas.DataFrame({
'k': ['a', 'b', 'q'],
'y': [10, 20, 30],
})
d_right
d_right = pandas.DataFrame({ 'k': ['a', 'b', 'q'], 'y': [10, 20, 30], }) d_right
d_right = pandas.DataFrame({
  'k': ['a', 'b', 'q'],
  'y': [10, 20, 30],
})

d_right
Out[12]:
ky
0a10
1b20
2q30
To perform a join we specify which set of columns our our row-matching conditions (using the
by
by argument) and what type of join we want (using the
jointype
jointype argument). For example we can use
jointype = 'LEFT'
jointype = 'LEFT' to augment our
d_left
d_left table with additional values from
d_right
d_right.

In [13]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ops = describe_table(d_left, table_name = 'd_left'). \
natural_join(b = describe_table(d_right, table_name = 'd_right'),
by = 'k',
jointype = 'LEFT')
ops.eval({'d_left': d_left, 'd_right': d_right})
ops = describe_table(d_left, table_name = 'd_left'). \ natural_join(b = describe_table(d_right, table_name = 'd_right'), by = 'k', jointype = 'LEFT') ops.eval({'d_left': d_left, 'd_right': d_right})
ops = describe_table(d_left, table_name = 'd_left'). \
  natural_join(b = describe_table(d_right, table_name = 'd_right'),
               by = 'k',
               jointype = 'LEFT')

ops.eval({'d_left': d_left, 'd_right': d_right})
Out[13]:
kxy
0a1.01.0
1aNaN10.0
2b3.020.0
In a left-join (as above) if the right-table has unique keys then we get a table with the same structure as the left-table- but with more information per row. This is a very useful type of join in data science projects. Notice columns with matching names are coalesced into each other, which we interpret as “take the value from the left table, unless it is missing.”

General conversion of record layouts

Record transformation is “simple once you get it”. However, we suggest reading up on that as a separate topic here.

Composing operations

We could, of course, perform complicated data manipulation by sequencing

data_algebra
data_algebra operations, and saving intermediate values.
data_algebra
data_algebra operators can also act on
data_algebra
data_algebra pipelines instead of acting on data. We can write our operations as follows.

We can use the

wrap()
wrap()/
ex()
ex() pattern to capture both the operator pipeline and to apply it.

In [14]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrapped_ops = wrap(d). \
extend({
'row_number': '_row_number()',
},
partition_by = ['x'],
order_by = ['y', 'z']). \
select_rows(
'row_number == 1') . \
drop_columns(
"row_number")
wrapped_ops.underlying
wrapped_ops = wrap(d). \ extend({ 'row_number': '_row_number()', }, partition_by = ['x'], order_by = ['y', 'z']). \ select_rows( 'row_number == 1') . \ drop_columns( "row_number") wrapped_ops.underlying
wrapped_ops = wrap(d). \
  extend({
         'row_number': '_row_number()',
         },
         partition_by = ['x'],
         order_by = ['y', 'z']). \
  select_rows(
              'row_number == 1') . \
  drop_columns(
               "row_number")

wrapped_ops.underlying
Out[14]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
TableDescription(
table_name='data_frame',
column_names=[
'x', 'y', 'z']) .\
extend({
'row_number': '_row_number()'},
partition_by=['x'],
order_by=['y', 'z']) .\
select_rows('row_number == 1') .\
drop_columns(['row_number'])
TableDescription( table_name='data_frame', column_names=[ 'x', 'y', 'z']) .\ extend({ 'row_number': '_row_number()'}, partition_by=['x'], order_by=['y', 'z']) .\ select_rows('row_number == 1') .\ drop_columns(['row_number'])
TableDescription(
 table_name='data_frame',
 column_names=[
   'x', 'y', 'z']) .\
   extend({
    'row_number': '_row_number()'},
   partition_by=['x'],
   order_by=['y', 'z']) .\
   select_rows('row_number == 1') .\
   drop_columns(['row_number'])
In [15]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
wrapped_ops.ex()
wrapped_ops.ex()
wrapped_ops.ex()
Out[15]:
xyz
0147
1238
data_algebra
data_algebra operators can also act on
data_algebra
data_algebra pipelines instead of acting on data. We can write our operations as follows:

In [16]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ops = describe_table(d). \
extend({
'row_number': '_row_number()',
},
partition_by = ['x'],
order_by = ['y', 'z']). \
select_rows(
'row_number == 1') . \
drop_columns(
"row_number")
ops
ops = describe_table(d). \ extend({ 'row_number': '_row_number()', }, partition_by = ['x'], order_by = ['y', 'z']). \ select_rows( 'row_number == 1') . \ drop_columns( "row_number") ops
ops = describe_table(d). \
  extend({
         'row_number': '_row_number()',
         },
         partition_by = ['x'],
         order_by = ['y', 'z']). \
  select_rows(
              'row_number == 1') . \
  drop_columns(
               "row_number")

ops
Out[16]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
TableDescription(
table_name='data_frame',
column_names=[
'x', 'y', 'z']) .\
extend({
'row_number': '_row_number()'},
partition_by=['x'],
order_by=['y', 'z']) .\
select_rows('row_number == 1') .\
drop_columns(['row_number'])
TableDescription( table_name='data_frame', column_names=[ 'x', 'y', 'z']) .\ extend({ 'row_number': '_row_number()'}, partition_by=['x'], order_by=['y', 'z']) .\ select_rows('row_number == 1') .\ drop_columns(['row_number'])
TableDescription(
 table_name='data_frame',
 column_names=[
   'x', 'y', 'z']) .\
   extend({
    'row_number': '_row_number()'},
   partition_by=['x'],
   order_by=['y', 'z']) .\
   select_rows('row_number == 1') .\
   drop_columns(['row_number'])
And we can re-use this pipeline, both on local data and to generate
SQL
SQL to be run in remote databases. Applying this operator pipeline to our
DataFrame
DataFrame
d
d is performed as follows.

In [17]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ops.transform(d)
ops.transform(d)
ops.transform(d)
Out[17]:
xyz
0147
1238
What we are trying to illustrate above: there is a continuum of notations possible between:

  • Working over values with explicit intermediate variables.
  • Working over values with a pipeline.
  • Working over operators with a pipeline.

Being able to see these as all related gives some flexibility in decomposing problems into solutions. We have some more advanced notes on the differences in working modalities here and here.

Conclusion

data_algebra
data_algebra supplies a very teachable grammar of data manipulation based on Codd’s relational algebra and experience with pipelined data transforms (such as
base::transform()
base::transform(),
dplyr
dplyr,
data.table
data.table,
Pandas
Pandas, and
rquery
rquery).

For in-memory situations

data_algebra
data_algebra uses
Pandas
Pandas as the implementation provider.

For bigger than memory situations

data_algebra
data_algebra can translate to any sufficiently powerful
SQL
SQL dialect, allowing
data_algebra
data_algebra pipelines to be executed on PostgreSQL, Apache Spark, or Google BigQuery.

In addition the

rquery R package supplies a nearly identical system for working with data in R. The two systems can even share data manipulation code between each other (allowing very powerful R/Python inter-operation or helping port projects from one to the other).

In [ ]:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
 
To leave a comment for the author, please follow the link and comment on their blog: python – Win-Vector Blog .

Want to share your content on python-bloggers? click here.