We’ve had really good progress in bringing the `Python` `data_algebra` to feature parity with `R` `rquery`. In fact we are able to reproduced the New Introduction to `rquery` article as a “New Introduction to the `data_algebra`” here.

The idea is: you may have good reasons to want to work in `R` or to want to work in `Python`. And Win-Vector LLC wants to leave the choice of `R` versus `Python` to you, by providing equivalent strong tools for each platform.

In the article below notice we can explore the same concepts in `R` or in `Python` (with a different syntax emphasizing quotation and method-chaining, to be more natively “Pythonic”).

## Introduction to the `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`‘s `base::transform()`, `dplyr`‘s `dplyr::mutate()`, or `rquery`‘s `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` “window functions.” More on the background and context of `data_algebra` can be found here.

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

In transform formulations data manipulation is written as transformations that produce new `DataFrame`s, instead of as alterations of a primary data structure (as is the case with `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`‘s case the primary set of data operators is as follows:

• `drop_columns`
• `select_columns`
• `rename_columns`
• `select_rows`
• `order_rows`
• `extend`
• `project`
• `natural_join`
• `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`s.
• 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` 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` interface, such as PostgreSQL, Apache Spark, or Google BigQuery).

We will work through simple examples/demonstrations of the `data_algebra` data manipulation operators.

## `data_algebra` operators

### Simple column operations (selecting and re-naming columns)

The simple column operations are as follows.

• `drop_columns`
• `select_columns`
• `rename_columns`

These operations are easy to demonstrate.

We set up some simple data.

In :
```import pandas

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

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

In :
```from data_algebra.data_ops import *

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

`select_columns`‘s action is also obvious from example.

In :
```wrap(d). \
select_columns(['x', 'y']). \
ex()
```
Out:
xy
015
114
223
`rename_columns` is given as name-assignments of the form `'new_name': 'old_name'`:

In :
```wrap(d). \
rename_columns({
'x_new_name': 'x',
'y_new_name': 'y'
}). \
ex()
```
Out:
x_new_namey_new_namez
0156
1147
2238

### Simple row operations (selecting and re-ordering rows)

The simple row operations are:

• `select_rows`
• `order_rows`

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

In :
```wrap(d). \
select_rows('x == 1'). \
ex()
```
Out:
xyz
0156
1147
`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` argument). Multiple columns can be selected in the order, each column breaking ties in the earlier comparisons.

In :
```wrap(d). \
order_rows(
['x', 'y'],
reverse = ['x']). \
ex()
```
Out:
xyz
0238
1147
2156
General `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` accepts arbitrary expressions to create new columns (or replace existing ones). For example:

In :
```wrap(d). \
extend({'zzz': 'y / x'}). \
ex()
```
Out:
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` allows for very powerful per-group operations akin to what `SQL` calls “window functions”. When the optional `partitionby` argument is set to a vector of column names then aggregate calculations can be performed per-group. For example.

In :
```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:
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`) and in the order determined by the `orderby` argument (without the `orderby` argument order is not guaranteed, so always set `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` is:

• `project`

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

In :
```wrap(d). \
project({
'max_y': 'y.max()',
'count': '_size()',},
group_by = ['x']). \
ex()
```
Out:
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` columns.

In :
```wrap(d). \
project({
'max_y': 'y.max()',
'count': '_size()',
}). \
ex()
```
Out:
max_ycount
053

### Combining results between two `DataFrame`s

To combine multiple tables in `data_algebra` one uses what we call the `natural_join` operator. In the `data_algebra` `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 :
```d_left = pandas.DataFrame({
'k': ['a', 'a', 'b'],
'x': [1, None, 3],
'y': [1, None, None],
})

d_left
```
Out:
kxy
0a1.01.0
1aNaNNaN
2b3.0NaN
In :
```d_right = pandas.DataFrame({
'k': ['a', 'b', 'q'],
'y': [10, 20, 30],
})

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

In :
```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:
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` operations, and saving intermediate values.
`data_algebra` operators can also act on `data_algebra` pipelines instead of acting on data. We can write our operations as follows.

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

In :
```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:
```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 :
```wrapped_ops.ex()
```
Out:
xyz
0147
1238
`data_algebra` operators can also act on `data_algebra` pipelines instead of acting on data. We can write our operations as follows:

In :
```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:
```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` to be run in remote databases. Applying this operator pipeline to our `DataFrame` `d` is performed as follows.

In :
```ops.transform(d)
```
Out:
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` supplies a very teachable grammar of data manipulation based on Codd’s relational algebra and experience with pipelined data transforms (such as `base::transform()`, `dplyr`, `data.table`, `Pandas`, and `rquery`).

For in-memory situations `data_algebra` uses `Pandas` as the implementation provider.

For bigger than memory situations `data_algebra` can translate to any sufficiently powerful `SQL` dialect, allowing `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 [ ]:
```
```