Welcome to pandastable documentation.

Contents:

Introduction

The pandastable library provides a table widget for Tkinter with plotting and data manipulation functionality. It uses the pandas DataFrame class to store table data. Pandas is an open source Python library providing high-performance data structures and data analysis tools. Tkinter is the standard GUI toolkit for python. It is intended for the following uses:

  • for python/tkinter GUI developers who want to include a table in their application that can store and process large amounts of data
  • for non-programmers who are not familiar with Python or the pandas API and want to use the included DataExplore application to manipulate/view their data
  • it may also be useful for data analysts and programmers who want to get an initial interactive look at their tabular data without coding

Current Features

  • add, remove rows and columns
  • spreadsheet-like drag, shift-click, ctrl-click selection
  • edit individual cells
  • sort by column, rename columns
  • reorder columns dynamically by mouse drags
  • set some basic formatting such as font, text size and column width
  • save the DataFrame to supported pandas formats
  • import/export of supported text files
  • rendering of very large tables is only memory limited
  • interactive plots with matplotlib, mostly using the pandas plot functions
  • basic table manipulations like aggregate and pivot
  • filter table using built in dataframe functionality
  • graphical way to perform split-apply-combine operations

The DataExplore application

Installing the package creates a command dataexplore in your path. Just run this to open the program. This is a standalone application for data manipulation and plotting meant for education and basic data analysis. More details are in the ‘Using dataexplore’ section. Also see the home page for this application at http://dmnfarrell.github.io/pandastable/

Citation

If you use this software in your work please cite the following article:

Farrell, D 2016 DataExplore: An Application for General Data Analysis in Research and Education. Journal of Open Research Software, 4: e9, DOI: http://dx.doi.org/10.5334/jors.94

Installation

For Dataexplore

For Windows users there is an MSI installer for the DataExplore application. This is recommended for anyone using windows not using the library directly as a widget.

On linux snaps are highly recommended:

snap install dataexplore

pandastable library

On all operating systems installations of Python should include the pip tool. If not use your distributions package manager to install pip first. Then a simple call as follows should install all dependencies:

pip install pandastable

This might not work well in some cases because matplotlib has library dependencies that users might find confusing. Though it should work ok on recent versions of Ubuntu. Advice for each OS is given below.

Dependencies

  • numpy
  • pandas
  • matplotlib
  • numexpr

Optional dependencies

  • statsmodels
  • seaborn (requires scipy)

Linux

For the python linbrary using easy_install or pip should work well but for matplotlib might require more packages such as python headers for compiling the extension. You need the tk8.6-dev package to provide the tkagg backend.

Otherwise, to use the package manager in Ubuntu/Debian based distributions you can issue the command:

sudo apt install python-matplotlib

You should install pandas with pip as it will provide the most recent version. This will likely be done automatically anyway:

For python 3 installs

You need to use the command pip3 instead if python 2 is also on your system, like in Ubuntu. When installing packages with apt you likely need to specify python 3. e.g. python3-numpy instead of python-numpy.

For python 2.7 ONLY

You will also need the future package. Run pip install future to install them. Python 2.6 has NOT been tested and probably won’t work.

Windows

It is much easier to install matplotlib in windows using the binary installer rather than using pip. You can download this [here](http://matplotlib.org/downloads.html). Pick the appropriate file for your python version e.g. ‘matplotlib-1.4.3.win32-py3.4.exe’ for python 3.4.

pandas should install ok with the pip installer. In windows pip.exe is located under C:Python34Scripts. The future package is needed for python 2.7.

Note that the Python pydata stack can also be installed at once using miniconda, http://conda.pydata.org/miniconda.html. This includes a version of Python itself.

Mac OSX

There are multiple packaged installers for scientific Python, the best of which is probably anaconda. Miniconda is a smaller version if you don’t want all the packages. To use it download and run the Mac OS X installer from http://conda.pydata.org/miniconda.html. The installer will automatically configure your system to use the Anaconda Python. You can then use pip to install the package.

If using macports:

sudo port install py34-pip
sudo pip-3.4 install matplotlib numpy pandas numexpr

Using the source distribution file

You can download the latest tar.gz file [here](https://github.com/dmnfarrell/pandastable/releases/latest/) and do the following:

tar -xzvf pandastable.version.tar.gz
cd pandastable
sudo python3 setup.py install

Note that you still need to have installed the dependencies as above.

Using DataExplore

This page details some of the tasks available in dataexplore. For a general introduction also see the screencast at https://youtu.be/Ss0QIFywt74. Most of this functionality is available when you just use the table widget as well as the dataexplore application. Installing in windows or with a snap in linux should provide a menu item to launch the app. Otherwise use the command line, detailed below.

Purpose of the program

This program is for analyzing tabular data but is not meant to be a spreadsheet. Data is treated in a row/column centric fashion and a lot of the analysis is done in bulk on entire columns at once. So although you can edit cells it is not really meant for data entry. You can use a spreadsheet for that. Cell formulas are not possible for instance. You can however delete rows, columns and clear blocks of cells. New columns can be created through the use of functions. The primary goal is to let users explore their tables interactively without any prior programming knowledge and make interesting plots as they do this. One advantage is the ability to load and work with relatively large tables as compared to spreadsheets. So several million rows should not be a problem and is limited only by your computer memory.

Table layout

The table is laid out with headers for row and columns. Much functionality can be accessed from the tools menu but also but right clicking on the row and column headers. You can resize columns by dragging in the header. Rows cannot be resized independently (zoom in to enlarge). Unlike spreadsheets column and ro headers can use indexes. You can set any column as an index. This has extra functionality when it comes to plotting.

_images/table_overview.png

Command Line

Launching dataexplore from the command line allows you to provide several options using unix type ‘-’ switches.

Show help:

dataexplore -h

Open a project file:

dataexplore -p <project file>

Open a dataframe stored as a messagepack file:

dataexplore -f <msgpack file>

Open a csv file and try to import it:

dataexplore -i <csv file>

Launch a basic test table with no plot frame

dataexplore -t

Import text files

Import of csv and general plain text formats is done from the file menu, toolbar or by right-clicking anywhere in the table and using the context menu. The dialog has most basic options such as delimiter, header selection, comment symbol, rows to skip etc. When you change the import option you can update the preview to see if the new table will look correct. You then press import. Note that it is generally a good idea to remove empty lines and bad data if you can before importing.

Saving data

Dataexplore projects (multiple groups of sheets with the plot view for each) are saved in messagepack format and have the .dexpl file extension. Tables can also be saved on their own as messagepack or pickle files and then opened directly in Python. Using the messagepack format is more efficient than csv as it takes up less space and loads faster. Though quite reliable and efficient, it is not recommended that you use these formats for long term backup, always keep a copy your raw data if it is important. Exporting to csv is also possible and saving individual tables to excel.

Getting table info

The status bar at the bottom left shows the size of the table in rows and columns at all times. For a more detailed summary use Tools->Table info. This brings up a window showing the type of each column and memory usage. ‘object’ columns are those with text/mixed data and float and int must be numbers only.

_images/table_info.png

Cleaning data

Pandas supports a variety of options for data ‘cleaning’ or dealing with missing data. The most basic are available from DataExplore from the main menu.

  • Drop rows/columns with missing (empty) data
  • Fill missing data with a symbol
  • Forward or backfill with neighbouring row values
  • Interpolate missing data (filling in the points between)
  • Drop duplicates

String operations

Accessed by right clicking on the column header menu. String operations can be carried out on any column as long as they are object data types and not pure numbers.

The following string methods are supported:

  • split, with separator symbol - will create multiple new columns
  • strip, remove whitespace
  • lower/upper case conversion
  • title, convert to TitleCase
  • swap case
  • get length of string
  • concat, concatenate strings in first two cols with given separator
  • slice, slice string by start/end indexes
  • replace

Summarizing and grouping data

For overall table statistics you can use the tools->describe table command. For individual columns you can get value counts by right clicking on the header.

The primary way to summarize data is to use the aggregate dialog. It is accessed on the right toolbar. Tables can be grouped and aggregated on multiple columns to create new summary tables. The results will be placed in the sub table below the main one and can then be copied to new sheets. Normally you would group by category columns (rather then a continuous variable like decimal numbers). The dialog has a list of columns to group by and another list box for column(s) to aggregate these groups using one or more functions. See the animated example (click to enlarge):

_images/agg_dialog_example.gif

It is often easiest to test the selections out until you get the required result.

Merging two tables

Merging tables is done in dataexplore by first putting your second table in the sub-table below. You can do that by pasting it from another sheet or making an empty sub-table and importing. Once this is done you open the merge dialog in the toolbar. You select which columns in each table to merge on (at least one columns should be shared between each). The apply and the result is opened in the dialog to preview. You can copy this to a new sheet.

Pivoting tables

Pivot tables is an operation some people might be familiar with from excel. A pivot might best be described as way of summarizing data by ‘unstacking’ the grouped data into new columns. It is a more specialized version of the aggregation method above. A comprehensive explanation is given here: https://www.dataquest.io/blog/pandas-pivot-table/

Transpose tables

A transpose is rotating the table on its axes so the rows become columns and vice versa. This can be useful for plotting purposes when you want to treat the row data as series. This is illustrated in the animation below where the same table is plotted first with the years as series and then with ‘col1’ and ‘col2’ as series and years as data points. Your row index will become the new columns when you transpose, so you should make sure the correct index is set beforehand. If you make a mistake you can undo or transpose again to reverse. Note: transposing extremely large tables might be slow.

_images/transpose_example.gif

Filtering tables

Filtering tables is done using either a string query and/or one or more pre-defined filters defined with widgets.

Query with widgets

Pressing the filtering button will bring up the dialog below the table. Manual predefined filters can be added by pressing the + button. These are used alone or in conjunction with the string query as shown below. The filters are joined together using the first menu item using either ‘AND’, ‘OR’ or ‘NOT’ boolean logic. When filtered results are found the found rows are highlighted. You can also limit the table to show the filtered set which can be treated as usual (i.e. plots made etc). Closing the query box restores the full table. If you want to keep the filtered table you can copy and paste in another sheet.

String query

String based query are made up fairly intuitive expressions. The one caveat is that column names cannot contain spaces to be used in an expression. It is best in these cases to convert column names (i.e. replace spaces with an underscore ‘_’). You may also use Python/pandas style expressions to perform filters, useful with string based queries.

Examples:

x>4 and y<3 #filter by values of columns x and y
x.str.contains("abc") #find only values of column x containing substring #abc
x.str.len()>3 #find only rows where length of strings in x is greater than 3
_images/filtering_example.gif

Applying functions

Unlike a spreadsheet there are no cell based formulas. Rather functions are applied to columns over all rows, creating a new column. New columns can be created in several ways through computations on other columns. The column header menu provides some of these like resample/transform a column or the apply function dialog. Another more general way to add functions is to use the calculation button on the toolbar. This brings up a dialog below the table where you can type function as text expressions.

The same as for filtering, a string is entered like a formula and if it can be parsed a new column is created. For example entering ‘x = a + b’ will create a new column x that is the sum of a and b.

Examples:

x = a+b  #sum a and b
x = a*a  #a squared
x = sin(a)
x = sqrt(a+b)/log(c)

Supported functions in expressions: sin, cos, tan, arcsin, arccos, arctan, sinh, cosh, tanh, log, log10, exp

Converting column names

It may sometimes be necessary to re-format column names, for example to remove unwanted characters. If you have dozens or more columns this would be time consuming, so there is a function in dataexplore to do this in one step. Accessed from Tools->Convert column names, this dialog allows you to replace characters e.g. replace spaces with ‘_’ symbol. You can also convert cases.

Resampling columns

Resampling is a way to average data over specific windows or periods. It is a possible way to smooth out noisy data for example or get an average trend. You can resample columns from the column header menu. In the example below this is used to smooth out the sawtooth shaped C02 data. The larger the window the more averaging will take place.

_images/resample_example.gif

Plot options

The plot frame has an options dialog underneath with multiple tabs grouped by functionality. Most default formatting options such as the type of plot, whether to show a legend etc. are in the first tab. The dialogs may look a bit cluttered for some users but the idea is to have all available options quickly accessible rather than hidden in menus. If you use the program regularly you will be familiar with where things are. Some of the less obvious options are explained in the image below.

_images/plot_options.png

The following plot types are currently supported:

  • line
  • scatter
  • bar
  • barh
  • pie
  • histogram
  • box plot
  • dot plot
  • heatmap
  • area
  • hexbin
  • contour
  • scatter matrix
  • venn

Other tabs contain options for grid layouts, text annotation such as titles and text boxes, and access to the plot animation settings.

Plotting grouped data

Rather than grouping the table directly it is also possible to plot data grouped. This requires you select the appropriate columns including the one to be grouped by and select the grouping column in the ‘groupby’ menu in the plot options. Plots can be grouped by 2 columns at once.

Plotting in a grid

The gif animation below shows how to use the grid layout tool to generate subplots by clicking and dragging in the grid to select the area for your next plot. Note that subplots will be overwritten if you select the same cell as one currently occupied but if you drag over this cell the region will be plotted over. The tool assumes the user will know how to avoid overlaps. So it’s best to have a good idea of how to layout the plots beforehand, or just use trial and error. You can remove subplots from the drop down menu, listed according to their positions.

_images/grid_layout_example.gif

Grid layout includes other modes ‘split data and ‘multiview’. Split data lets you pick a grid size and splits up the rows into chunks, plotting each separately. The multiview mode allows you to auto-generate different kinds of plot in the grid for the same data every time you plot. This could be useful for quickly previewing regions of data repeatedly without having to set the plot type each time. This will overwrite whatever plot you currently have displayed. The feature is also illustrated in the gif above.

Animated plots

Plots can be animated and save as video files using the plot animation options tab. This would mostly be useful for time series based line plots but any kinds of plots can be animated. Formatting can be changed or column selections altered as the plot is updating, leading to some odd plot displays.

see http://dmnfarrell.github.io/dataexplore/2018/05/15/animation

Table Coloring

Column colors can be set by right clicking in the column header and choosing ‘set color’. A color picker will open. The formatting is saved with the project file. You can clear the formatting from the table popup menu.

You can set row and cell colors in several ways. Firstly, if right clicking on the row header or inside the table the ‘set color’ option lets you color the selected rows/columns with a single color. You can also set colors for the entire table/column according to the cell values. This is done by choosing ‘color by value’ from the column header and will allow you to select a color map. String values will be mapped to categorical integers and then to colors. See below:

_images/table_colors.png

For very large tables, adding colors for all cells will increases the file size of saved projects.

Setting preferences

Preferences for table formatting can be set from the edit->preferences menu item. This uses a text configuration file stored in ~/.dataexplore/default.conf. The preferences dialog is used to apply the settings to the current table and/or save them to this file. This file can be edited manually in a text editor if you wish. Any new tables will use these settings. The file looks like this:

[base]
align = w
cellwidth = 80
floatprecision = 2
font = Arial
fontsize = 12
linewidth = 1
rowheight = 22

[colors]
cellbackgr = #F4F4F3
grid_color = #ABB1AD
rowselectedcolor = #E4DED4
textcolor = black

Batch processing

A plugin provides the ability to batch import and/or plot multiple files at once. This is generally designed for many similarly formatted files that you wish to clean or plot in bulk without loading each individually. You can also use this to join many files into one table. Access this tool from Plugins->Batch Process.

Code Examples

This section is for python programmers you want to use the table widget in their own programs.

Basics

Create a parent frame and then add the table to it:

from tkinter import *
from pandastable import Table
#assuming parent is the frame in which you want to place the table
pt = Table(parent)
pt.show()

Update the table:

#alter the DataFrame in some way, then update
pt.redraw()

Import a csv file:

pt.importCSV('test.csv')

A class for launching a basic table in a frame:

from tkinter import *
from pandastable import Table, TableModel, config

class TestApp(Frame):
        """Basic test frame for the table"""
        def __init__(self, parent=None):
            self.parent = parent
            Frame.__init__(self)
            self.main = self.master
            self.main.geometry('600x400+200+100')
            self.main.title('Table app')
            f = Frame(self.main)
            f.pack(fill=BOTH,expand=1)
            df = TableModel.getSampleData()
            self.table = pt = Table(f, dataframe=df,
                                    showtoolbar=True, showstatusbar=True)
                        pt.show()
                        #set some options
                        options = {'colheadercolor':'green','floatprecision': 5}
                        config.apply_options(options, pt)
            pt.show()
            return

app = TestApp()
#launch the app
app.mainloop()

Sub-class the Table

Override the right click popup menu:

class MyTable(Table):
    """Custom table class inherits from Table. You can then override required methods"""
    def __init__(self, parent=None, **kwargs):
        Table.__init__(self, parent, **kwargs)
        return

          def handle_left_click(self, event):
        """Example - override left click"""

        Table.handle_left_click(self, event)
  #do custom code here
        return

    def popupMenu(self, event, rows=None, cols=None, outside=None):
        """Custom right click menu"""

        popupmenu = Menu(self, tearoff = 0)
        def popupFocusOut(event):
            popupmenu.unpost()
                                # add commands here
    # self.app is a reference to the parent app
        popupmenu.add_command(label='do stuff', command=self.app.stuff)
        popupmenu.bind("<FocusOut>", popupFocusOut)
        popupmenu.focus_set()
        popupmenu.post(event.x_root, event.y_root)
        return popupmenu

Table methods

You can use the Table class methods to directly access data and perform many more functions. Check the API for all the methods. Some examples are given here:

#add 10 empty columns
table.autoAddColumns(10)
#resize the columns to fit the data better
table.autoResizeColumns()
#clear the current formatting
table.clearFormatting()
#reduce column witdths proportionally
table.contractColumns()
#get selected column
table.getSelectedColumn()
#sort by column index 0
table.sortTable(0)
#enlarge all table elements
table.zoomIn()
#set row colors
table.setRowColors(rows=range(2,100,2), clr='lightblue', cols='all')
#delete selected rows
table.setSelectedRows([[4,6,8,10]])
#delete current row
table.deleteRow()
#set current row
table.setSelectedRow(10)
#insert below current row
table.insertRow()

Accessing and modifying data directly

The tables use a pandas DataFrame object for storing the underlying data. If you are not familiar with pandas you should learn the basics if you need to access or manipulate the table data. See http://pandas.pydata.org/pandas-docs/stable/10min.html

Each table has an object called model with has the dataframe inside it. The dataframe is referred to as df. So to access the data on a table you can use:

df = table.model.df

Examples of simple dataframe operations. Remember when you update the dataframe you will need to call table.redraw() to see the changes reflected:

df.drop(0) #delete column with this index
df.T #transpose the DataFrame
df.drop(columns=['x'])

Set table attributes

You can set table attributes directly such as these examples:

            table.textcolor = 'blue'
            table.cellbackgr = 'white'
            table.boxoutlinecolor = 'black'
            #set header colors
            self.table.rowheader.bgcolor = 'orange'
            self.table.colheader.bgcolor = 'lightgreen'
            self.table.colheader.textcolor = 'black'
            #make editable or not
table.editable = False

Set Preferences

Preferences are normally loaded from a configuration file that can be edited manually or via the menu. You can also programmatically set these preferences using the config module:

#load from a config file if you need to (done by default when tables are created)
options = config.load_options()
#options is a dict that you can set yourself
options = {'floatprecision': 2}
config.apply_options(options, table)

You can set the following configuration values:

{'align': 'w',
 'cellbackgr': '#F4F4F3',
 'cellwidth': 80,
 'floatprecision': 2,
 'thousandseparator': '',
 'font': 'Arial',
 'fontsize': 12,
 'fontstyle': '',
 'grid_color': '#ABB1AD',
 'linewidth': 1,
 'rowheight': 22,
 'rowselectedcolor': '#E4DED4',
 'textcolor': 'black'}

Table Coloring

You can set column colors by setting the key in the columncolors dict to a valid hex color code. Then just redraw:

table.columncolors['mycol'] = '#dcf1fc' #color a specific column
table.redraw()

You can set row and cell colors in several ways. table.rowcolors is a pandas dataframe that mirrors the current table and stores a color for each cell. It only adds columns as needed. You can update this manually but it is easiest to use the following methods:

table.setRowColors(rows, color) #using row numbers
table.setColorByMask(column, mask, color) #using a pre-defined mask
table.redraw()

To color by column values:

table.multiplecollist = [cols] #set the selected columns
table.setColorbyValue()
table.redraw()

To clear formatting:

table.clearFormatting()
table.redraw()

Note: You should generally use a simple integer index for the table when using colors as there may be inconsistencies otherwise.

Writing DataExplore Plugins

Plugins are for adding custom functionality that is not present in the main application. They are implemented by sub-classing the Plugin class in the plugin module. This is a python script that can generally contain any code you wish. Usually the idea will be to implement a dialog that the user interacts with. But this could also be a single method that runs on the current table or all sheets at once.

Implementing a plugin

Plugins should inherit from the Plugin class. Though this is not strictly necessary for the plugin to function.

from pandastable.plugin import Plugin

You can simply copy the example plugin to get started. All plugins need to have a main() method which is called by the application to launch them. By default this method contains the _doFrame() method which constructs a main frame as part of the current table frame. Usually you override main() and call _doFrame then add your own custom code with your widgets.

_doFrame method has the following lines which are always needed unless it is a non GUI plugin:

self.table = self.parent.getCurrentTable() #get the current table
#add the plugin frame to the table parent
self.mainwin = Frame(self.table.parentframe)
#pluginrow is 6 to make the frame appear below other widgets
self.mainwin.grid(row=pluginrow,column=0,columnspan=2,sticky='news')

You can also override the quit() and about() methods.

Non-table based plugins

Plugins that don’t rely on using the table directly do not need to use the above method and can have essentially anything in them as long as there is a main() method present. The Batch File Rename plugin is an example. This is a standalone utility launched in a separate toplevel window.

see https://github.com/dmnfarrell/pandastable/blob/master/pandastable/plugins/rename.py

Freezing the app

Dataexplore is available as an exe with msi installer for Windows. This was created using the cx_freeze package. For anyone wishing to freeze their tkinter app some details are given here. This is a rather hit and miss process as it seems to depend on your installed version of Python. Even when the msi/exe builds you need to check for runtime issues on another copy of windows to make sure it’s working. Steps:

  • Use a recent version of python (>=3.6 recommended) installed as normal and then using pip to install the dependencies that you normally need to run the app.
  • The freeze script is found in the main pandastable folder, freeze.py. You can adopt it for your own app.
  • Run the script using python freeze.py bdist_msi
  • The resulting msi is placed in the dist folder. This is a 32 bit binary but should run fine on windows 10.

You can probably use Anaconda to do the same thing but we have not tested this.

pandastable

pandastable package

Submodules

pandastable.annotation module

pandastable.app module

pandastable.core module

Implements the core pandastable classes. Created Jan 2014 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

class pandastable.core.ChildToolBar(parent=None, parentapp=None)[source]

Bases: pandastable.core.ToolBar

Smaller toolbar for child table

class pandastable.core.Table(parent=None, model=None, dataframe=None, width=None, height=None, rows=20, cols=5, showtoolbar=False, showstatusbar=False, editable=True, enable_menus=True, **kwargs)[source]

Bases: tkinter.Canvas

A tkinter class for providing table functionality.

Parameters:
  • parent – parent Frame
  • model – a TableModel with some data
  • dataframe – a pandas DataFrame
  • width – width of frame
  • height – height of frame
  • rows – number of rows if creating empty table
  • cols – number of columns if creating empty table
  • showtoolbar – whether to show the toolbar, default False
  • showstatusbar – whether to show the statusbar
addColumn(newname=None)[source]

Add a new column

addRows(num=None)[source]

Add new rows

adjustColumnWidths(limit=30)[source]

Optimally adjust col widths to accomodate the longest entry in each column - usually only called on first redraw. :param limit: max number of columns to resize

aggregate()[source]

Show aggregate dialog

applyColumnFunction(evt=None)[source]

Apply column wise functions, applies a calculation per row and ceates a new column.

applyStringMethod()[source]

Apply string operation to column(s)

applyTransformFunction(evt=None)[source]

Apply resampling and transform functions on a single column.

autoAddColumns(numcols=None)[source]

Automatically add x number of cols

autoResizeColumns()[source]

Automatically set nice column widths and draw

checkDataEntry(event=None)[source]

do validation checks on data entry in a widget

cleanData()[source]

Deal with missing data

clearData(evt=None)[source]

Delete cells from gui event

clearFormatting()[source]
clearSelected()[source]

Clear selections

clearTable()[source]

Make an empty table

close(evt=None)[source]
closeChildTable()[source]

Close the child table

colorColumns(cols=None, color='gray')[source]

Color visible columns

colorRows()[source]

Color individual cells in column(s). Requires that the rowcolors dataframe has been set. This needs to be updated if the index is reset

contractColumns(factor=10)[source]

Reduce column widths

convertColumnNames(s='_')[source]

Convert col names so we can use numexpr

convertDates()[source]

Convert single or multiple columns into datetime

convertNumeric()[source]

Convert cols to numeric if possible

copy(rows, cols=None)[source]

Copy cell contents from clipboard - overwrites table.

copyColumn()[source]

Copy a column

copyIndex()[source]

Copy index to a column

copyTable(event=None)[source]

Copy from the clipboard

corrMatrix()[source]

Correlation matrix

createCategorical()[source]

Get a categorical column from selected

createChildTable(df, title=None, index=False, out=False)[source]

Add the child table

crosstab()[source]

Cross tabulation

deleteCells(rows, cols, answer=None)[source]

Clear the cell contents

deleteColumn(ask=True)[source]

Delete currently selected column(s)

deleteRow(ask=False)[source]

Delete a selected row

describe()[source]

Create table summary

doBindings()[source]

Bind keys and mouse clicks, this can be overriden

doCombine()[source]

Do combine/merge operation

doExport(filename=None)[source]

Do a simple export of the cell contents to csv

drawCellEntry(row, col, text=None)[source]

When the user single/double clicks on a text/number cell, bring up entry window and allow edits.

drawGrid(startrow, endrow)[source]

Draw the table grid lines

drawHighlighted()[source]

Color an arbitrary selection of cells. Set the ‘highlighted’ attribute which is a masked dataframe of the table.

drawMultipleCells()[source]

Draw an outline box for multiple cell selection

drawMultipleCols()[source]

Draw multiple column selections

drawMultipleRows(rowlist)[source]

Draw more than one row selection

drawRect(row, col, color=None, tag=None, delete=1)[source]

Cell is colored

drawRowHeader()[source]

User has clicked to select a cell

drawSelectedCol(col=None, delete=1, color=None, tag='colrect')[source]

Draw a highlight rect for the current column selection

drawSelectedRect(row, col, color=None, fillcolor=None)[source]

User has clicked to select a cell

drawSelectedRow()[source]

Draw a highlight rect for the currently selected rows

drawText(row, col, celltxt, align=None, single_line=True)[source]

Draw the text inside a cell area

duplicateRows()[source]

Make copy of rows

evalBar(evt=None)[source]

Use pd.eval to apply a function colwise or preset funcs.

evalFunction(evt=None)[source]

Apply a function to create new columns

expandColumns(factor=10)[source]

Reduce column widths

fillAcross(collist, rowlist)[source]

Fill across a row, or multiple rows

fillColumn()[source]

Fill a column with a data range

fillDown(rowlist, collist)[source]

Fill down a column, or multiple columns

findDuplicates()[source]

Find duplicate rows

findText(evt=None)[source]

Simple text search in whole table

flattenIndex()[source]

Flatten multiindex

functionsBar(evt=None)[source]

Apply python functions from a pre-defined set, this is for stuff that can’t be done with eval strings

getCanvasPos(row, col)[source]

Get the cell x-y coords as a fraction of canvas size

getCellCoords(row, col)[source]

Get x-y coordinates to drawing a cell in a given row/col

getColPosition(x)[source]

Get column position at coord

getFonts()[source]
getGeometry(frame)[source]

Get frame geometry

getPlotData()[source]

Plot data from selection

getRowPosition(y)[source]

Set row position

getRowsFromIndex(idx=None)[source]

Get row positions from index values

getRowsFromMask(mask)[source]
getScale()[source]
getSelectedColumn()[source]

Get currently selected column

getSelectedDataFrame()[source]

Return a sub-dataframe of the selected cells. Will try to convert object types to float so that plotting works.

getSelectedRow()[source]

Get currently selected row

getSelectedRowData()[source]

Return a sub-dataframe of the selected rows

getSelectionValues()[source]

Get values for current multiple cell selection

getVisibleCols(x1, x2)[source]

Get the visible column range

getVisibleRegion()[source]

Get visible region of canvas

getVisibleRows(y1, y2)[source]

Get the visible row range

get_col_clicked(event)[source]

Get column where event on the canvas occurs

get_memory()[source]

memory usage of current table

get_row_clicked(event)[source]

Get row where event on canvas occurs

gotonextCell()[source]

Move highlighted cell to next cell in row or a new col

gotonextRow()[source]

Programmatically set next row - eg. for button events

gotoprevRow()[source]

Programmatically set previous row - eg. for button events

groupby(colindex)[source]

Group by

handleCellEntry(row, col)[source]

Callback for cell entry

handleEntryMenu(*args)[source]

Callback for option menu in categorical columns entry

handle_arrow_keys(event)[source]

Handle arrow keys press

handle_double_click(event)[source]

Do double click stuff. Selected row/cols will already have been set with single click binding

handle_left_click(event)[source]

Respond to a single press

handle_left_ctrl_click(event)[source]

Handle ctrl clicks for multiple row selections

handle_left_release(event)[source]

Handle left mouse button release event

handle_left_shift_click(event)[source]

Handle shift click, for selecting multiple rows

handle_mouse_drag(event)[source]

Handle mouse moved with button held down, multiple selections

handle_right_click(event)[source]

respond to a right click

hidePlot()[source]

Hide plot frame

hideRowHeader()[source]

Hide the row header, must have run show() first

importCSV(filename=None, dialog=False, **kwargs)[source]

Import from csv file

importHDF(filename=None, dialog=False, **kwargs)[source]
insertRow()[source]

Insert a new row

isInsideTable(x, y)[source]

Returns true if x-y coord is inside table bounds

load(filename=None)[source]

load from a file

loadExcel(filename=None)[source]

Load excel file

loadPrefs(prefs=None)[source]

Load preferences from defaults

melt()[source]

Melt table

merge(table)[source]

Merge with another table.

mouse_wheel(event)[source]

Handle mouse wheel scroll for windows

moveColumns(names=None, pos='start')[source]

Move column(s) to start/end, used for large tables

movetoSelection(row=None, col=0, idx=None, offset=0)[source]

Move to a specific row/col, updating table

new()[source]

Clears all the data and makes a new table

paste(event=None)[source]

Paste a new table from the clipboard

pivot()[source]

Pivot table

placeColumn(col1, col2)[source]

Move col1 next to col2, useful for placing a new column made from the first one next to it so user can see it easily

plot3D()[source]
plotSelected()[source]

Plot the selected data in the associated plotviewer

popupMenu(event, rows=None, cols=None, outside=None)[source]

Add left and right click behaviour for canvas, should not have to override this function, it will take its values from defined dicts in constructor

query(evt=None)[source]

Do query

queryBar(evt=None)[source]

Query/filtering dialog

recalculateFunctions(omit=None)[source]

Re evaluate any columns that were derived from functions and dependent on other columns (except self derived?)

redraw(event=None, callback=None)[source]

Redraw table

redrawCell(row=None, col=None, recname=None, colname=None)[source]

Redraw a specific cell only

redrawVisible(event=None, callback=None)[source]

Redraw the visible portion of the canvas. This is the core redraw method. Refreshes all table elements. Called by redraw() method as shorthand.

Parameters:
  • event – tkinter event to trigger method, default None
  • callback – function to be called after redraw, default None
remove()[source]

Close table frame

renameIndex()[source]

Rename the row index

resample()[source]

Table time series resampling dialog. Should set a datetime index first.

resetColors()[source]
resetIndex(ask=True, drop=False)[source]

Reset index and redraw row header

resizeColumn(col, width)[source]

Resize a column by dragging

resized(event)[source]

Check if size changed when event triggered to avoid unnecessary redraws

save()[source]

Save current file

saveAs(filename=None)[source]

Save dataframe to file

selectAll(evt=None)[source]

Select all rows and cells

selectNone()[source]

Deselect current, called when table is redrawn with completely new cols and rows e.g. after model is updated.

setAlignment(colnames=None)[source]

Set column alignments, overrides global value

setColPositions()[source]

Determine current column grid positions

setColorByMask(col, mask, clr)[source]

Color individual cells in a column using a mask.

setColorbyValue()[source]

Set row colors in a column by values

setColumnColors(cols=None, clr=None)[source]

Set a column color and store it

setColumnType()[source]

Change the column dtype

setFont()[source]

Set font tuple

setPrecision(x, p)[source]

Set precision of a float value

setRowColors(rows=None, clr=None, cols=None)[source]

Set rows color from menu. :param rows: row numbers to be colored :param clr: color in hex :param cols: column numbers, can also use ‘all’

setRowHeight(h)[source]

Set the row height

setSelectedCells(startrow, endrow, startcol, endcol)[source]

Set a block of cells selected

setSelectedCol(col)[source]

Set currently selected column

setSelectedRow(row=None)[source]

Set currently selected row and reset multiple row list

setSelectedRows(rows)[source]
setTheme(name='light')[source]

Set theme

setWrap()[source]

Toogle column header wrap

set_defaults()[source]

Set default settings

set_rowcolors_index()[source]
set_xviews(*args)[source]

Set the xview of table and col header

set_yviews(*args)[source]

Set the xview of table and row header

setcellbackgr()[source]
setgrid_color()[source]
setindex()[source]

Set indexes

setrowselectedcolor()[source]

Set selected row color

show(callback=None)[source]

Adds column header and scrollbars and combines them with the current table adding all to the master frame provided in constructor. Table is then redrawn.

showAll()[source]

Re-show unfiltered

showIndex()[source]

Show the row index

showInfo()[source]

Show dataframe info

showPlot()[source]
showPlotViewer(parent=None)[source]

Create plot frame

showPreferences()[source]

Preferences dialog

showRowHeader()[source]

Show the row header if hidden, must have run show() first

show_progress_window(message=None)[source]

Show progress bar window for loading of data

showasText()[source]

Get table as formatted text - for printing

sortColumnIndex()[source]

Sort the column header by the current rows values

sortTable(columnIndex=None, ascending=1, index=False)[source]

Sort rows based on currently selected columns

statsViewer()[source]

Show model fitting dialog

storeCurrent()[source]

Store current version of the table before a major change is made

tableChanged()[source]

Callback to be used when dataframe changes so that other widgets and data can be updated

tableFromSelection()[source]

Create a new table from the selected cells

transform()[source]

Apply element-wise transform

transpose()[source]

Transpose table

undo(event=None)[source]

Undo last major table change

updateFunctions()[source]

Remove functions if a column has been deleted

updateModel(model=None)[source]

Should call this method when a new table model is loaded. Recreates widgets and redraws the table.

updateWidgets()[source]

Update some dialogs when table changed

update_rowcolors()[source]

Update row colors if present so that it syncs with current dataframe.

valueCounts()[source]

Value counts for column(s)

values_to_colors(x, cmap='jet', alpha=1)[source]

Convert columnn values to colors

zoomIn()[source]

Zoom in, increases font and row heights.

zoomOut()[source]

Zoom out, decreases font and row heights.

class pandastable.core.ToolBar(parent=None, parentapp=None)[source]

Bases: tkinter.ttk.Frame

Uses the parent instance to provide the functions

class pandastable.core.statusBar(parent=None, parentapp=None)[source]

Bases: tkinter.ttk.Frame

Status bar class

update()[source]

Update status bar

pandastable.data module

Module implementing the Data class that manages data for it’s associated PandasTable.

Created Jan 2014 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

class pandastable.data.TableModel(dataframe=None, rows=20, columns=5)[source]

Bases: object

A data model for the Table class that uses pandas

Parameters:
  • dataframe – pandas dataframe
  • rows – number of rows if empty table
  • columns – number of columns if empty table
addColumn(colname=None, dtype=None, data=None)[source]

Add a column

autoAddRows(num)[source]

Add n rows to end of dataframe. Will create rows with index starting from highest previous row count

copyIndex()[source]

Copy index to a column

deleteCells(rows, cols)[source]
deleteColumn(colindex)[source]

delete a column

deleteColumns(cols=None)[source]

Remove all cols or list provided

deleteRow(row, unique=True)[source]

Delete a row

deleteRows(rowlist=None, unique=True)[source]

Delete multiple or all rows

filterby()[source]
getColumnCount()[source]

Returns the number of columns in the data model

getColumnName(columnIndex)[source]

Returns the name of the given column by columnIndex

getColumnType(columnIndex)[source]

Get the column type

classmethod getIrisData()[source]

Get iris dataset

getRecordAtRow(rowindex)[source]

Get the entire record at the specifed row

getRowCount()[source]

Returns the number of rows in the table model.

classmethod getSampleData(rows=400, cols=5, n=2)[source]

Generate sample data :param rows: no. of rows :param cols: columns :param n: length of column names

classmethod getStackedData()[source]

Get a dataframe to pivot test

getValueAt(row, col)[source]

Returns the cell value at location specified by columnIndex and rowIndex.

getlongestEntry(colindex, n=500)[source]

Get the longest string in the column for determining width. Just uses the first n rows for speed

groupby(cols)[source]

Group by cols

initialiseFields()[source]

Create meta data fields

insertRow(row)[source]

Inserts a row at the required index by append/concat

keywords = {'colors': 'colors'}
load(filename, filetype=None)[source]

Load file, if no filetype given assume it’s pickle format

moveColumn(oldindex, newindex)[source]

Changes the order of columns

query()[source]
resetIndex(drop=False)[source]

Reset index behaviour

save(filename)[source]

Save dataframe

setValueAt(value, row, col, df=None)[source]

Change dataframe according to row/col numbers. You can also pass an arbitrary dataframe here.

setindex(colindex)[source]

Index setting behaviour

setup(dataframe, rows=20, columns=5)[source]

Create table model

transpose()[source]

Transpose dataframe

pandastable.dialogs module

Dialog classes. Created Oct 2014 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

class pandastable.dialogs.AggregateDialog(parent=None, df=None)[source]

Bases: pandastable.dialogs.BaseDialog

Provides a frame for split-apply-combine operations

apply()[source]

Apply operation

copyResult()[source]
createWidgets(m)[source]

Create a set of grp-agg-func options together

help()[source]

Help button code

quit()[source]

Quit the Tcl interpreter. All widgets will be destroyed.

class pandastable.dialogs.AutoScrollbar(master=None, **kw)[source]

Bases: tkinter.ttk.Scrollbar

A scrollbar that hides itself if it’s not needed. only works if you use the grid geometry manager.

pack(**kw)[source]
place(**kw)[source]
set(lo, hi)[source]

Set the fractional values of the slider position (upper and lower ends as value between 0 and 1).

class pandastable.dialogs.BaseDialog(parent=None, df=None, title='')[source]

Bases: tkinter.ttk.Frame

Generic dialog - inherit from this and customise the createWidgets and apply methods.

apply()[source]

Code to run when Apply is pressed

buttonsFrame()[source]
createWidgets(m)[source]

Override this

help()[source]

Help button code

quit()[source]

Quit the Tcl interpreter. All widgets will be destroyed.

class pandastable.dialogs.BaseTable(parent=None, width=280, height=190, rows=2, cols=2, **kwargs)[source]

Bases: tkinter.Canvas

Basic table class based on tk canvas. inherit from this to add your own functionality

doBindings()[source]
drawGrid()[source]
drawMultipleCells(rows, cols)[source]

Draw more than one row selection

drawSelectedRect(row, col, color='#c2c2d6', pad=4, tags='')[source]

User has clicked to select area

getCellCoords(row, col)[source]

Get x-y coordinates to drawing a cell in a given row/col

get_col_clicked(event)[source]

Get column where event on the canvas occurs

get_row_clicked(event)[source]

Get row where event on canvas occurs

handle_left_click(event)[source]

Respond to a single press

handle_mouse_drag(event)[source]

Handle mouse moved with button held down, multiple selections

redraw()[source]
update()[source]

Enter event loop until all pending events have been processed by Tcl.

class pandastable.dialogs.CombineDialog(parent=None, df1=None, df2=None)[source]

Bases: tkinter.ttk.Frame

Provides a frame for setting up merge/combine operations

apply()[source]

Apply operation

getResult(df)[source]

Show result of merge and let user choose to replace current table

help()[source]
quit()[source]

Quit the Tcl interpreter. All widgets will be destroyed.

replaceTable()[source]

replace parent table

class pandastable.dialogs.CrosstabDialog(parent=None, df=None, title='')[source]

Bases: pandastable.dialogs.BaseDialog

apply()[source]

Apply crosstab

createWidgets(m)[source]

Create a set of grp-agg-func options together

help()[source]

Help button code

class pandastable.dialogs.EasyListbox(parent, width, height, yscrollcommand, listItemSelected)[source]

Bases: tkinter.Listbox

Customised list box to replace useless default one

clear()[source]

Deletes all items from the list box.

getIndex(item)[source]

Returns the index of item if it’s in the list box.

getSelectedIndex()[source]

Returns the index of the selected item or -1 if no item is selected.

getSelectedItem()[source]

Returns the selected item or the empty string if no item is selected.

setSelectedIndex(index)[source]

Selects the item at the index if it’s in the range.

triggerListItemSelected(event)[source]

Strategy method to respond to an item selection in the list box. Runs the client’s listItemSelected method with the selected index.

class pandastable.dialogs.FilterBar(parent, parentframe, cols)[source]

Bases: tkinter.ttk.Frame

Class providing filter widgets

booleanops = ['AND', 'OR', 'NOT']
close()[source]

Destroy and remove from parent

getFilter()[source]

Get filter values for this instance

operators = ['contains', 'excludes', 'equals', 'not equals', '>', '<', 'is empty', 'not empty', 'starts with', 'ends with', 'has length', 'is number', 'is lowercase', 'is uppercase']
update(cols)[source]

Enter event loop until all pending events have been processed by Tcl.

class pandastable.dialogs.FindReplaceDialog(table)[source]

Bases: tkinter.ttk.Frame

Find/replace dialog.

clear()[source]
close()[source]
find()[source]

Do string search. Creates a masked dataframe for results and then stores each cell coordinate in a list.

findAll()[source]

Highlight all found cells

findNext()[source]

Show next cell of search results

replace()[source]

Replace all instances of search text

setup()[source]
updated(name='', index='', mode='')[source]

Widgets changed so run search again

class pandastable.dialogs.ImportDialog(parent=None, filename=None)[source]

Bases: tkinter.ttk.Frame

Provides a frame for figure canvas and MPL settings

doImport()[source]

Do the import

quit()[source]

Quit the Tcl interpreter. All widgets will be destroyed.

showText(encoding='utf-8')[source]

Show text contents

update()[source]

Reload previews

class pandastable.dialogs.MultipleValDialog(parent, title=None, initialvalues=None, labels=None, types=None, tooltips=None, width=14, **kwargs)[source]

Bases: tkinter.simpledialog.Dialog

Simple dialog to get multiple values

apply()[source]

process the data

This method is called automatically to process the data, after the dialog is destroyed. By default, it does nothing.

body(master)[source]

create dialog body.

return widget that should have initial focus. This method should be overridden, and is called by the __init__ method.

getResults(null=None)[source]

Return a dict of options/values

class pandastable.dialogs.Progress(parent, side='left')[source]

Bases: object

threaded progress bar for tkinter gui

pb_clear()[source]

stops the progress bar

pb_complete()[source]

stops the progress bar and fills it

pb_start()[source]

starts the progress bar

pb_stop()[source]

stops the progress bar

class pandastable.dialogs.ProgressDialog[source]

Bases: tkinter.Toplevel

class pandastable.dialogs.QueryDialog(table)[source]

Bases: tkinter.ttk.Frame

Use string query to filter. Will not work with spaces in column names, so these would need to be converted first.

addFilter()[source]

Add a filter using widgets

applyFilter(df, mask=None)[source]

Apply the widget based filters, returns a boolean mask

close()[source]
colorResult()[source]

Color filtered rows in main table

query(evt=None)[source]

Do query

setup()[source]
update()[source]

Enter event loop until all pending events have been processed by Tcl.

class pandastable.dialogs.SimpleEditor(parent=None, width=100, height=40, font=None)[source]

Bases: tkinter.ttk.Frame

Simple text editor

onClear()[source]

Clear text

onFind()[source]
onSave()[source]

Save text

class pandastable.dialogs.ToolTip(widget)[source]

Bases: object

Tooltip class for tkinter widgets

classmethod createToolTip(widget, text)[source]

Create a tooltip for a widget

hidetip(event=None)[source]

Hide tooltip

showtip(text, event=None)[source]

Display text in tooltip window

class pandastable.dialogs.VerticalScrolledFrame(parent, height=None, width=None, *args, **kw)[source]

Bases: tkinter.ttk.Frame

A pure Tkinter scrollable frame see http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame. Use the ‘interior’ attribute to place widgets inside the scrollable frame.

pandastable.dialogs.addButton(frame, name, callback, img=None, tooltip=None, side='top', compound=None, width=None, padding=1)[source]

Add a button with image, toolip to a tkinter frame

pandastable.dialogs.addListBox(parent, values=[], width=10, height=6, label='')[source]

Add an EasyListBox

pandastable.dialogs.applyStyle(w)[source]

Apply style to individual widget to prevent widget color issues on linux

pandastable.dialogs.dialogFromOptions(parent, opts, groups=None, callback=None, sticky='news', layout='horizontal')[source]

Auto create tk vars and widgets for corresponding options and and return the enclosing frame

pandastable.dialogs.getBestGeometry(win, width=None)[source]

Calculate optimal geometry from screen size or given width

pandastable.dialogs.getDictfromTkVars(opts, tkvars, widgets)[source]
pandastable.dialogs.getListBoxSelection(w)[source]
pandastable.dialogs.getParentGeometry(parent)[source]
pandastable.dialogs.pickColor(parent, oldcolor)[source]
pandastable.dialogs.setGeometry(win, width=None)[source]

Set window geometry to center of screen

pandastable.dialogs.setWidgetStyles(widgets)[source]

set styles of list of widgets

pandastable.handlers module

Module for plot viewer event classes.

Created Jan 2016 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

class pandastable.handlers.DragHandler(parent, figure=None)[source]

Bases: object

A simple class to handle picking and dragging

button_press_event(event)[source]
connect()[source]

Connect events

disconnect()[source]

disconnect all the stored connection ids

drawSelectionRect()[source]

Draw a selection box

key_press_event(event)[source]

Handle key press

on_pick_event(event)[source]

Store which text object was picked and were the pick event occurs.

on_release_event(event)[source]

Update and store text/annotation position

pandastable.headers module

Implements the pandastable headers classes. Created Jan 2014 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

class pandastable.headers.ColumnHeader(parent=None, table=None, bg='gray25')[source]

Bases: tkinter.Canvas

Class that takes it’s size and rendering from a parent table and column names from the table model.

drawRect(col, tag=None, color=None, outline=None, delete=1)[source]

User has clicked to select a col

draw_resize_symbol(col)[source]

Draw a symbol to show that col can be resized when mouse here

handle_double_click(event)[source]

Double click sorts by this column.

handle_left_click(event)[source]

Does cell selection when left mouse button is clicked

handle_left_ctrl_click(event)[source]

Handle ctrl clicks - for multiple column selections

handle_left_release(event)[source]

When mouse released implement resize or col move

handle_left_shift_click(event)[source]

Handle shift click, for selecting multiple cols

handle_mouse_drag(event)[source]

Handle column drag, will be either to move cols or resize

handle_mouse_move(event)[source]

Handle mouse moved in header, if near divider draw resize symbol

handle_right_click(event)[source]

respond to a right click

handle_right_release(event)[source]
leave(event)[source]

Mouse left canvas event

popupMenu(event)[source]

Add left and right click behaviour for column header

redraw(align='w')[source]

Redraw column header

renameColumn()[source]

Rename column

setDefaults()[source]
within(val, l, d)[source]

Utility funtion to see if val is within d of any items in the list l

class pandastable.headers.IndexHeader(parent=None, table=None, width=40, height=25, bg='gray50')[source]

Bases: tkinter.Canvas

Class that displays the row index headings.

handle_left_click(event)[source]

Handle mouse left mouse click

redraw(align='w')[source]

Redraw row index header

class pandastable.headers.RowHeader(parent=None, table=None, width=50, bg='gray75')[source]

Bases: tkinter.Canvas

Class that displays the row headings (or DataFrame index). Takes it’s size and rendering from the parent table. This also handles row/record selection as opposed to cell selection

clearSelected()[source]

Clear selected rows

drawRect(row=None, tag=None, color=None, outline=None, delete=1)[source]

Draw a rect representing row selection

drawSelectedRows(rows=None)[source]

Draw selected rows, accepts a list or integer

handle_left_click(event)[source]

Handle left click

handle_left_ctrl_click(event)[source]

Handle ctrl clicks - for multiple row selections

handle_left_release(event)[source]
handle_left_shift_click(event)[source]

Handle shift click

handle_mouse_drag(event)[source]

Handle mouse moved with button held down, multiple selections

handle_right_click(event)[source]

respond to a right click

popupMenu(event, rows=None, cols=None, outside=None)[source]

Add left and right click behaviour for canvas, should not have to override this function, it will take its values from defined dicts in constructor

redraw(align='w', showkeys=False)[source]

Redraw row header

setWidth(w)[source]

Set width

toggleIndex()[source]

Toggle index display

pandastable.headers.createSubMenu(parent, label, commands)[source]

pandastable.images module

Images stored as PhotoImage objects, for buttons and logos. Created Oct 2008 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

pandastable.images.accept()[source]
pandastable.images.add()[source]
pandastable.images.add_col()[source]
pandastable.images.add_row()[source]
pandastable.images.aggregate()[source]
pandastable.images.calculate()[source]
pandastable.images.color_swatch()[source]
pandastable.images.contract_col()[source]
pandastable.images.copy()[source]
pandastable.images.cross()[source]
pandastable.images.del_col()[source]
pandastable.images.del_row()[source]
pandastable.images.delete()[source]
pandastable.images.end()[source]
pandastable.images.excel()[source]
pandastable.images.expand_col()[source]
pandastable.images.filtering()[source]
pandastable.images.fit()[source]
pandastable.images.font()[source]
pandastable.images.function()[source]
pandastable.images.importcsv()[source]
pandastable.images.melt()[source]
pandastable.images.merge()[source]
pandastable.images.new_proj()[source]
pandastable.images.next()[source]
pandastable.images.open_proj()[source]
pandastable.images.paste()[source]
pandastable.images.pivot()[source]
pandastable.images.plot()[source]
pandastable.images.plot_clear()[source]
pandastable.images.plot_prefs()[source]
pandastable.images.prefs()[source]
pandastable.images.prev()[source]
pandastable.images.refresh()[source]
pandastable.images.save()[source]
pandastable.images.save_proj()[source]
pandastable.images.search()[source]
pandastable.images.start()[source]
pandastable.images.table_delete()[source]
pandastable.images.table_multiple()[source]
pandastable.images.tilehorizontal()[source]
pandastable.images.tilevertical()[source]
pandastable.images.transpose()[source]
pandastable.images.zoom_in()[source]
pandastable.images.zoom_out()[source]

pandastable.plotting module

Module for pandastable plotting classes .

Created Jan 2014 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

class pandastable.plotting.AnimateOptions(parent=None)[source]

Bases: pandastable.plotting.TkOptions

Class for live update/animation of plots.

addWidgets()[source]

Custom dialogs for manually adding annotation items like text

getWriter()[source]
showDialog(parent, layout='horizontal')[source]

Create dialog widgets

start()[source]

start animation using a thread

stop()[source]

Stop animation loop

stream()[source]

Stream data into table and plot - not implemented yet

update()[source]

do live updating

updateCurrent(writer=None)[source]

Iterate over current table and update plot

class pandastable.plotting.AnnotationOptions(parent=None)[source]

Bases: pandastable.plotting.TkOptions

This class also provides custom tools for adding items to the plot

addArrow(kwds=None, key=None)[source]

Add line/arrow

addObject()[source]

Add an annotation object

addTextBox(kwds=None, key=None)[source]

Add a text annotation and store it using key

addWidgets()[source]

Custom dialogs for manually adding annotation items like text

clear()[source]

Clear annotations

redraw()[source]

Redraw all stored annotations in the right places after a plot update

showDialog(parent, layout='horizontal')[source]

Override because we need to add custom widgets

class pandastable.plotting.ExtraOptions(parent=None)[source]

Bases: pandastable.plotting.TkOptions

Class for additional formatting options like styles

addWidgets()[source]

Custom dialogs for manually adding annotation items like text

apply()[source]
reset()[source]
showDialog(parent, layout='horizontal')[source]

Create dialog widgets

class pandastable.plotting.MPL3DOptions(parent=None)[source]

Bases: pandastable.plotting.MPLBaseOptions

Class to provide 3D matplotlib options

applyOptions()[source]

Set the plot kwd arguments from the tk variables

defaultfont = 'monospace'
kinds = ['scatter', 'bar', 'contour', 'wireframe', 'surface']
class pandastable.plotting.MPLBaseOptions(parent=None)[source]

Bases: pandastable.plotting.TkOptions

Class to provide a dialog for matplotlib options and returning the selected prefs

applyOptions()[source]

Set the plot kwd arguments from the tk variables

defaultfont = 'monospace'
kinds = ['line', 'scatter', 'bar', 'barh', 'pie', 'histogram', 'boxplot', 'violinplot', 'dotplot', 'heatmap', 'area', 'hexbin', 'contour', 'imshow', 'scatter_matrix', 'density', 'radviz', 'venn']
legendlocs = ['best', 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center']
update(df)[source]

Update data widget(s) when dataframe changes

class pandastable.plotting.PlotLayoutGrid(parent=None, width=280, height=205, rows=2, cols=2, **kwargs)[source]

Bases: pandastable.dialogs.BaseTable

handle_left_click(event)[source]

Respond to a single press

class pandastable.plotting.PlotLayoutOptions(parent=None)[source]

Bases: pandastable.plotting.TkOptions

resetGrid(event=None)[source]

update grid and redraw

setmultiviews(event=None)[source]
showDialog(parent, layout='horizontal')[source]

Override because we need to add custom bits

updateAxesList()[source]

Update axes list

updateFromGrid()[source]
class pandastable.plotting.PlotViewer(table, parent=None, showoptions=True)[source]

Bases: tkinter.ttk.Frame

Provides a frame for figure canvas and MPL settings.

Parameters:
  • table – parent table, required
  • parent – parent tkinter frame
  • layout – ‘horizontal’ or ‘vertical’
addWidgets()[source]

Add option widgets to control panel

applyPlotoptions()[source]

Apply the current plotter/options

autoscale(axis='y')[source]

Set all subplots to limits of largest range

bar3D(data, ax, kwds)[source]

3D bar plot

checkColumnNames(cols)[source]

Check length of column names

clear()[source]

Clear plot

close()[source]

Close the window

contourData(data)[source]

Get data for contour plot

dotplot(df, ax, kwds)[source]

Dot plot

getView()[source]
getcmap(name)[source]
heatmap(df, ax, kwds)[source]

Plot heatmap

meshData(x, y, z)[source]

Prepare 1D data for plotting in the form (x,y)->Z

plot2D(redraw=True)[source]

Plot method for current data. Relies on pandas plot functionality if possible. There is some temporary code here to make sure only the valid plot options are passed for each plot kind.

plot3D(redraw=True)[source]

3D plot

plotCurrent(redraw=True)[source]

Plot the current data

plotMultiViews(plot_types=['bar', 'scatter'])[source]

Plot multiple views of the same data in a grid

plotSplitData()[source]

Splits selected data up into multiple plots in a grid

removeSubplot()[source]

Remove a specific axis from the grid layout

replot(data=None)[source]

Re-plot using current parent table selection. Args: data: set current dataframe, otherwise use current table selection

savePlot(filename=None)[source]

Save the current plot

scatter(df, ax, alpha=0.8, marker='o', color=None, **kwds)[source]

A custom scatter plot rather than the pandas one. By default this plots the first column selected versus the others

scatter3D(data, ax, kwds)[source]

3D scatter plot

setAxisLabels(ax, kwds)[source]

Set a plots axis labels

setFigureOptions(axs, kwds)[source]

Set axis wide options such as ylabels, title

setGlobalOption(name='', *args)[source]

Set global value from widgets

setOption(option, value)[source]
setSubplotTitle()[source]

Set a subplot title if using grid layout

setupGUI()[source]

Add GUI elements

showWarning(text='plot error', ax=None)[source]

Show warning message in the plot window

toggle_options()[source]

Show/hide plot options

updateData()[source]

Update data widgets

updatePlot()[source]

Update the current plot with new options

updateStyle()[source]
updateWidgets()[source]

Set global widgets from values

venn(data, ax, colormap=None, alpha=0.8)[source]

Plot venn diagram, requires matplotlb-venn

violinplot(df, ax, kwds)[source]

violin plot

zoom(zoomin=True)[source]

Zoom in/out to plot by changing size of elements

class pandastable.plotting.TkOptions(parent=None)[source]

Bases: object

Class to generate tkinter widget dialog for dict of options

apply()[source]
applyOptions()[source]

Set the plot kwd arguments from the tk variables

increment(key, inc)[source]

Increase the value of a widget

setWidgetStyles()[source]
showDialog(parent, layout='horizontal')[source]

Auto create tk vars, widgets for corresponding options and and return the frame

updateFromDict(kwds=None)[source]

Update all widget tk vars using plot kwds dict

pandastable.plotting.addFigure(parent, figure=None, resize_callback=None)[source]

Create a tk figure and canvas in the parent frame

pandastable.plotting.get_defaults(name)[source]

pandastable.plugin module

Implements the dataexplore plugin class. Created Oct 2015 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

class pandastable.plugin.Plugin(parent=None)[source]

Bases: object

Base Plugin class, should be inherited by any plugin

capabilities = []
main(parent)[source]
menuentry = ''
quit(evt=None)[source]
requires = []
pandastable.plugin.describe_class(obj)[source]

Describe the class object passed as argument, including its methods

pandastable.plugin.describe_func(obj, method=False)[source]

Describe the function object passed as argument. If this is a method object, the second argument will be passed as True

pandastable.plugin.find_plugins()[source]
pandastable.plugin.get_plugins_classes(capability)[source]

Returns classes of available plugins

pandastable.plugin.get_plugins_instances(capability)[source]

Returns instances of available plugins

pandastable.plugin.init_plugin_system(folders)[source]
pandastable.plugin.load_plugins(plugins)[source]
pandastable.plugin.parsefolder(folder)[source]

Parse for all .py files in plugins folder or zip archive

pandastable.config module

Implements a configuration class for pandastable Created Oct 2015 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

pandastable.config.apply_options(options, table)[source]

Apply options to a table

pandastable.config.check_options(opts)[source]

Check for missing default options in dict. Meant to handle incomplete config files

pandastable.config.create_config_parser_from_dict(data=None, sections=odict_keys(['base', 'colors']), **kwargs)[source]

Helper method to create a ConfigParser from a dict of the form shown in baseoptions

pandastable.config.get_options(cp)[source]

Makes sure boolean opts are parsed

pandastable.config.load_options()[source]
pandastable.config.parse_config(conffile=None)[source]

Parse a configparser file

class pandastable.config.preferencesDialog(parent, options, table=None)[source]

Bases: tkinter.ttk.Frame

Preferences dialog from config parser options

apply()[source]

Apply options to current table

createWidgets()[source]

create widgets

quit()[source]

Quit the Tcl interpreter. All widgets will be destroyed.

save()[source]

Save from current dialog settings

updateFromOptions(options)[source]

Update all widget tk vars using dict

pandastable.config.print_options(options)[source]

Print option key/value pairs

pandastable.config.update_config(options)[source]
pandastable.config.write_config(conffile='default.conf', defaults={})[source]

Write a default config file

pandastable.config.write_default_config()[source]

Write a default config to users .config folder. Used to add global settings.

pandastable.stats module

Module for stats and fitting classes.

Created June 2015 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

class pandastable.stats.StatsViewer(table, parent=None)[source]

Bases: tkinter.ttk.Frame

Provides a frame for model viewing interaction

doFit()[source]

Do model fit on selected subset of rows. Will only use the currently selected rows for fitting.

getModel(formula, data, est='ols')[source]

Select model to use

guessFormula()[source]

Suggest a start formula

plotLogit(fit, indvar, ax, **kwds)[source]

Plot Logit results

plotPrediction(fit, ax)[source]

Plot predicted vs. test

plotRegression(fit, indvar, ax, **kwds)[source]

Plot custom statsmodels fit result for linear regression

quit()[source]

Quit the Tcl interpreter. All widgets will be destroyed.

setupGUI()[source]

Add GUI elements

showPlot()[source]

Do plots

summary()[source]

Fit summary

updateData()[source]

Update data widgets

pandastable.tests module

pandastable.util module

Implements the utility methods for pandastable classes. Created August 2015 Copyright (C) Damien Farrell

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

pandastable.util.adjustColorMap(cmap, minval=0.0, maxval=1.0, n=100)[source]

Adjust colormap to avoid using white in plots

pandastable.util.checkDict(d)[source]

Check a dict recursively for non serializable types

pandastable.util.checkOS()[source]

Check the OS we are in

pandastable.util.check_multiindex(index)[source]

Check if index is a multiindex

pandastable.util.colorScale(hex_color, brightness_offset=1)[source]

Takes a hex color and produces a lighter or darker variant. :returns: new color in hex format

pandastable.util.getAttributes(obj)[source]

Get non hidden and built-in type object attributes that can be persisted

pandastable.util.getFonts()[source]

Get the current list of system fonts

pandastable.util.getTextLength(text, w, font=None)[source]

Get correct canvas text size (chars) that will fit in a given canvas width

pandastable.util.setAttributes(obj, data)[source]

Set attributes from a dict. Used for restoring settings in tables

Module contents

Indices and tables