Tablesaw is easy to add to the BeakerX Groovy kernel. Tablesaw provides the ability to easily transform, summarize, and filter data, as well as computing descriptive statistics and fundamental machine learning algorithms.
This notebook has some basic demos of how to use Tablesaw, including visualizing the results. This notebook uses the Beaker interactive visualizaiton libraries, but Tablesaw's APIs also work. The notebook covers basic table manipulation, k-means clustering, and linear regression.
%%classpath add mvn
tech.tablesaw tablesaw-plot 0.21.0
tech.tablesaw tablesaw-beakerx 0.21.0
com.jimmoores quandl-tablesaw 2.0.0
com.github.haifengl smile-core 1.5.1
%import static tech.tablesaw.aggregate.AggregateFunctions.*
%import static tech.tablesaw.api.QueryHelper.*
%import tech.tablesaw.api.*
%import tech.tablesaw.columns.*
%import smile.clustering.*
%import smile.regression.*
// display Tablesaw tables with BeakerX table display widget
tech.tablesaw.beakerx.TablesawDisplayer.register()
tornadoes = Table.read().csv("../resources/data/tornadoes_2014.csv")
//print dataset structure
tornadoes.structure()
//get header names
tornadoes.columnNames()
//displays the row and column counts
tornadoes.shape()
//displays the first n rows
tornadoes.first(10)
tornadoes.structure().where(stringColumn("Column Type").isEqualTo("NUMBER"))
//summarize the data in each column
tornadoes.summary()
//Mapping operations
def month = tornadoes.dateColumn("Date").month()
tornadoes.addColumns(month);
tornadoes.columnNames()
//Sorting by column
tornadoes.sortOn("-Fatalities")
//Descriptive statistics
tornadoes.column("Fatalities").summary()
//Performing totals and sub-totals
def injuriesByScale = tornadoes.summarize("Injuries", median).by("Scale")
injuriesByScale.setName("Median injuries by Tornado Scale")
injuriesByScale
//Cross Tabs
//CrossTab.counts(tornadoes, tornadoes.stringColumn("State"), tornadoes.numberColumn("Scale"))
tornadoes.xTabCounts("State", "Scale")
K-means is the most common form of “centroid” clustering. Unlike classification, clustering is an unsupervised learning method. The categories are not predetermined. Instead, the goal is to search for natural groupings in the dataset, such that the members of each group are similar to each other and different from the members of the other groups. The K represents the number of groups to find.
We’ll use a well known Scotch Whiskey dataset, which is used to cluster whiskeys according to their taste based on data collected from tasting notes. As always, we start by loading data and printing its structure.
t = Table.read().csv("../resources/data/whiskey.csv")
t.structure()
kMeans = new KMeans(t.copy().retainColumns("Body", "Sweetness", "Smoky", "Medicinal", "Tobacco", "Honey", "Spicy", "Winey", "Nutty", "Malty", "Fruity", "Floral").asMatrix(), 5)
Table table = Table.create("Clusters");
StringColumn labelColumn = StringColumn.create("Label");
NumberColumn clusterColumn = DoubleColumn.create("Cluster");
table.addColumns(labelColumn);
table.addColumns(clusterColumn);
int[] clusters = kMeans.getClusterLabel();
for (int i = 0; i < clusters.length; i++) {
labelColumn.appendCell(t.stringColumn("distillery").getString(i));
clusterColumn.append(clusters[i]);
}
table = table.sortAscendingOn("Cluster", "Label");
In baseball, you make the playoffs by winning more games than your rivals. The number of games the rivals win is out of your control so the A’s looked instead at how many wins it took historically to make the playoffs. They decided that 95 wins would give them a strong chance. Here’s how we might check that assumption in Tablesaw.
baseball = Table.read().csv("../resources/data/baseball.csv");
// filter to the data available at the start of the 2002 season
moneyball = baseball.where(numberColumn("year").isLessThan(2002));
wins = moneyball.nCol("W");
year = moneyball.nCol("Year");
playoffs = moneyball.column("Playoffs");
runDifference = moneyball.numberColumn("RS").subtract(moneyball.numberColumn("RA"));
moneyball.addColumns(runDifference);
runDifference.setName("RD");
def Plot = new Plot(title: "RD x Wins", xLabel:"RD", yLabel: "W")
Plot << new Points(x: moneyball.numberColumn("RD").asDoubleArray(), y: moneyball.numberColumn("W").asDoubleArray())
winsModel = new OLS(moneyball.copy().retainColumns("W").asMatrix(), runDifference.asDoubleArray());
runsScored = new OLS(moneyball.copy().retainColumns("OBP", "SLG").asMatrix(), moneyball.nCol("RS").asDoubleArray());
new Histogram(xLabel:"X",
yLabel:"Proportion",
data: Arrays.asList(runsScored.residuals()),
binCount: 25);
%import com.jimmoores.quandl.*
%import com.jimmoores.quandl.tablesaw.*
TableSawQuandlSession session = TableSawQuandlSession.create();
Table table = session.getDataSet(DataSetRequest.Builder.of("WIKI/AAPL").build());
// Create a new column containing the year
NumberColumn yearColumn = table.dateColumn("Date").year();
yearColumn.setName("Year");
table.addColumns(yearColumn);
// Create max, min and total volume tables aggregated by year
Table summaryMax = table.summarize("Adj. Close", max).by("year");
Table summaryMin = table.summarize("Adj. Close", min).by("year");
Table summaryVolume = table.summarize("Volume", sum).by("year");
// Create a new table from each of these
summary = Table.create("Summary", summaryMax.column(0), summaryMax.column(1),
summaryMin.column(1), summaryVolume.column(1));
// Add back a DateColumn to the summary...will be used for plotting
DateColumn yearDates = DateColumn.create("YearDate");
for (year in summary.column('Year')) {
yearDates.append(java.time.LocalDate.of((int) year, 1, 1));
}
summary.addColumns(yearDates)
summary
years = summary.column('YearDate').collect()
plot = new TimePlot(title: 'Price Chart for AAPL', xLabel: 'Time', yLabel: 'Max [Adj. Close]')
plot << new YAxis(label: 'Volume')
plot << new Points(x: years, y: summary.column('Max [Adj. Close]').collect())
plot << new Line(x: years, y: summary.column('Max [Adj. Close]').collect(), color: Color.blue)
plot << new Stems(x: years, y: summary.column('Sum [Volume]').collect(), yAxis: 'Volume')