Home

Awesome

Pandashells

Introduction

For decades, system administrators, dev-ops engineers and data analysts have been piping textual data between unix tools like grep, awk, sed, etc. Chaining these tools together provides an extremely powerful workflow.

The more recent emergence of the "data-scientist" has resulted in the increasing popularity of tools like R, Pandas, IPython, etc. These tools have amazing power for transforming, analyzing and visualizing data-sets in ways that grep, awk, sed, and even the dreaded perl-one-liner could never accomplish.

Pandashells is an attempt to marry the expressive, concise workflow of the shell pipeline with the statistical and visualization tools of the python data-stack.

What is Pandashells?

If you work with data using Python, you have almost certainly encountered <a href="http://pandas.pydata.org/">Pandas</a>, <a href="http://www.scipy.org/">SciPy</a>, <a href="http://matplotlib.org/">Matplotlib</a>, <a href="http://statsmodels.sourceforge.net/">Statsmodels</a> and <a href="http://stanford.edu/~mwaskom/software/seaborn/">Seaborn</a>. Pandashells opens up a bash API into the python data stack with command syntax closely mirroring the underlying libraries on which it is built. This should allow those familiar with the python data stack to be immediately productive.

I would also like to call your attention to a related tool by Saul Pwanson: visidata.
Visidata is an interactive terminal-based app that excels at loading/transforming/summarizing tabular data from the command line.

Installation

Install with pip

Pandashells can be installed with pip, but a few words of caution are in order. First, you should really use a recent version of pip so you can access wheels on pypi pip install -U pip. Secondly, if your setup requires building from source rather than using wheels, you may run into problems with systems libraries being either out of date or missing. If you encounter these problems, you may want to use conda to install those dependencies.

Pandashells, no dependencies

Use this option if you want to completely manage your own dependencies. (See requirements section below).

<pre><code><strong> [~]$ pip install pandashells </strong></code></pre>

Pandashells console tools

Use this option to install Pandashells and only the console tools dependencies. This will not install the graphics dependencies (matplotlib and friends)

<pre><code><strong>[~]$ pip install pandashells[console]</strong></code></pre>

Pandashells full install

Use this option to install Pandashells and all dependencies

<pre><code><strong>[~]$ pip install pandashells[full]</strong></code></pre>

Requirements

Pandashells is both Python2 and Python3 compatible. There are no default requirements because some of the tools only require the standard library, and there's no sense installing unnecessary packages if you only want to use that subset of tools. If a particular tool encounters a missing dependency, it will fail with an error message indicating the missing dependency. Below is a list of all imports used across the Pandashells toolkit, and ordered according to install option.

Important: If you want to use pandashells without interactive visualizations (e. g. on a VM without X-forwarding), but would like to retain the ability to create static-image or html-based visualizations, you may need to configure pandashells to use the Agg backend as follows:

<pre><code>p.config --plot_backend Agg</code></pre>

Overview

All Pandashells executables begin with a "p." This is designed to work nicely with the bash-completion feature. If you can't remember the exact name of a command, simply typing p.[tab] will show you a complete list of all Pandashells commands.

Every command can be run with a -h option to view help. Each of these help messages will contain multiple examples of how to properly use the tool.

Pandashells is equipped with a tool to generate sample csv files. This tool provides standardized inputs for use in the tool help sections as well as this documentation.

<pre><code><strong>[~]$ p.example_data -h</strong></code></pre>

Tool Descriptions

Toolpip installPurpose
p.configpandashellsSet default Pandashells configuration options
p.cryptpandashellsEncrypt/decrypt files using open-ssl
p.formatpandashellsRender python string templates using input data
p.guipandashellsOpen dataframe in pandasgui interactive environment
p.parallelpandashellsRead shell commands from stdin and run them in parallel
p.example_datapandashellsCreate sample csv files for training/testing
p.dfpandashells[console]Pandas dataframe manipulation of text files
p.linspacepandashells[console]Generate a linearly spaced series of numbers
p.lomb_scarglepandashells[console]Generate Lomb-Scarge spectrogram of input time series
p.mergepandashells[console]Merge two data files by specifying join keys
p.randpandashells[console]Generate random numbers
p.regresspandashells[console]Perform (multi-variate) linear regression with R-like patsy syntax
p.sig_editpandashells[console]Remove outliers using iterative sigma-editing
p.smoothpandashells[console]Smooth data
p.cdfpandashells[full]Plot emperical distribution function
p.facet_gridpandashells[full]Create faceted plots for data exploration
p.histpandashells[full]Plot histograms
p.plotpandashells[full]Create xy plot visualizations
p.regplotpandashells[full]Quickly plot linear regression of data to a polynomial

DataFrame Manipulations

Pandashells allows you to specify multiple dataframe operations in a single command. Each operation assumes data is in a dataframe named df. Operations performed on this dataframe will overwrite the df variable with the results of that operation. Special consideration is taken for assignments such as df['a'] = df.b + 1. These are understood to make column assignments on df. By way of example, this command at the bash prompt:

p.df 'df["c"] = 2 * df.b' 'df.groupby(by="a").c.count()' 'df.reset_index()'

is equivalent to the following python snippet:

import pandas as pd
df = pd.read_csv(sys.stdin)
df["c"] = 2 * df.b
df = df.groupby(by="a").c.count()
df = df.reset_index()
df.to_csv(sys.stdout, index=False)

Shown below are several examples of how to use the p.df tool. You are encourage to copy/paste these commands to your bash prompt to see Pandashells in action.

</code></pre>

Join files on key fields

Pandashells can join files based on a set of key fields. This example uses only one field as a key, but like the pandas merge function on which it is based, multiple key fields can be used for the join.

Visualization Tools

Pandashells provides a number of visualization tools to help you quickly explore your data. All visualizations are automatically configured to show an interactive plot using the configured backend (default is TkAgg, but can be configured with the p.config tool).

As of version 0.2.0 pandashells supports the WebAgg backend for matplotlib. This enables interactive plots to be shown in a browser. To run with this option, set configuration with

p.config --plot_backend WebAgg

Note that WebAgg requires that Tornado be installed. This installation is left up to the user.

The visualizations can also be saved to image files (e.g. .png) or rendered to html. The html generated can either be opened directly in the browser to show an interactive plot (using mpld3), or can be embedded in an existing html file. The examples below show Pandashells-created png images along with the command used to generate them.

Spectral Estimation

Linear Regression

Pandashells leverages the excellent Seaborn and Statsmodels libraries to handle linear regression.

Further examples of each tool can be seen by calling it with the -h switch. You are encouraged to fully explore these examples. They highlight how Pandashells can be used to significantly improve your efficiency.

Simple Profiling Utility

In addition to command-line tools, Pandashells exposes a useful profiling tool that can be imported into your python code. The tools is just a simple context manager that sends timing information to stdout. The csv-like format of this output makes it easy to pipe through Pandashells pipelines. Here are a couple examples.

Profiling different parts of your code

Code

import time
from pandashells import Timer
with Timer('entire script'):
    for nn in range(3):
        with Timer('loop {}'.format(nn + 1)):
            time.sleep(.1 * nn)
# Will generate the following output on stdout
#     col1: a string that is easily found with grep
#     col2: the time in seconds (or in hh:mm:ss if pretty=True)
#     col3: the value passed to the 'name' argument of Timer

Output

__time__,2.6e-05,loop 1
__time__,0.105134,loop 2
__time__,0.204489,loop 3
__time__,0.310102,entire script

Profiling how code scales (measuring "big-O")

Code

import time
from pandashells import Timer

# initialize a list to hold results
results = []

# run a piece of code with different values of the var you want to scale
for nn in range(3):
    # time each iteration
    with Timer('loop {}'.format(nn + 1), silent=True) as timer:
        time.sleep(.1 * nn)
    # add results
    results.append((nn, timer))

# print csv compatible text for further pandashells processing/plotting
print 'nn,seconds'
for nn, timer in results:
    print '{},{}'.format(nn,timer.seconds)

Projects by robdmc.