Package: count-api
Count API DocumentationHarness the exploration, collaboration, and visualisation capabilities of thecount.coweb service in your workflow with theCount APIpackage for Python.This project contains an API client for thecount.coweb service, providing methods for authentication, data upload, and data visualisation.RequirementsPython 2 or 3Optimised for Jupyter Notebook environmentPackages installed as dependencies:requestsprotobufSupported versionsPython 2.7, 3.4, 3.5, 3.6.0, 3.6AccessIn order to use the Count API module, you need to generate a token in your accounts page oncount.co.InstallationIn your terminal, you can use pip to install count:pip install count_apipip3 install count_apiImportfrom count_api import CountAPIInitialisetoken="TOKEN GENERATED FROM COUNT.CO ADMIN PAGE"count=CountAPI()count.set_api_token(token)Load data to CountTablesIn the Count API, tables are objects that represent the data you are sending to Count.#Upload a File (.csv or .txt)path='Users/me/Downloads/norweiganCarSales.csv'table=count.upload(path=path,name='MyTableName')#Upload a dataframedf=pd.read_csv('norweiganCarSales.csv')table=count.upload(data=df,name='MyTableName')#Upload raw datatable=count.upload(data='Column1,Column2,Column3\n1,10,100\n2,20,200',name='MyTableName')Previewing table contentsThe first rows of a table can be printed to screen by using thetable.head(rows,columns)method, e.g.table.head()The last rows of a table can be printed to screen by using thetable.tail(rows,columns)method, e.g.table.tail()You can also find the number of rows in a column viatable.size()which returns a tuple of ints(number_of_rows, number_of_columns).Generate Count URLIf you want to visualise your table in Count, you'll need the URL. See the example scripts on examples of how to best use this URL to distribute to your team, and visualise for yourself.url=table.url()Create a VisualVisualsLike Table objects, Visual objects are created to represent a visual you have created with thetable.upload_visualmethod. Thetable.upload_visualmethod contains the following parameters;x,y,size,color: specify which column to plot on each axis, via the name of the column or the column object itselfaggregates: a tuple/list of tuples/dict of the column-to-aggregrate mapping specifying the aggregate to perform on each column. For example, for performing asumon a column named 'ColumnName1' and an 'avg' on a column namedColumnName2, you can use{'ColumnName1' : 'sum', 'ColumnName2' : 'avg'}groupings: a tuple/list of tuples/dict of the groupings to apply to a column. For example, to group adatetimecolumn by month you can use{'ColumnName1': 'month'}filters: a tuple/list of tuples/dict of the filters to apply to a column. For example, for filtering on adatetimecolum named 'Year' for values between the year 2007 and 2012, you can use `[('Year', '>=', (2007,)), ('Year', '<=', (2012,)]chart_options: a dict of chart options allowing specification of axis-scale e.g.{'x_type' : 'linear', 'y_type': 'log'}; chart type{'type' : 'circle'}.A full example snippet is shown below:visual=table.upload_visual(x='Year',y='Quantity',color='Type',filters=[('Year','>=',(2007,1,1)),('Year','<=',(2012,1))]aggregates={'Quantity','sum'},chart_options={'y_type':'linear','chart_type':'line'})Selecting columnsTo create a visual, you will need to reference the columns in the Table object. Column references are used for selecting axesx,y,color,size, constructing thefilters, selectingaggregatesandgroupings.CountAPI provides several ways to reference a column in the table.q_columns=table.columns('Quantity')# List of Column objects for columns with title matching string 'Quantity'q_column=table['Quantity']# Column object of first column with title matching string 'Quantity'col_type=table.column('Type')# Column object of first column with title matching string 'Type'first_column=table[0]# Column object of first column in tablefirst_column=table.column(0)# Column object of first column in tableYou can also use the column name directly in theupload_visualsignature itself, as shown in the example in thelinksection. Referencing columns directly via their names is equivalent to using thetable['ColumnName']form shown above.AxesVisuals oncount.cocan have the following axes:x,y,size,color.FiltersFilters can be represented as a tuple, a lists of tuples, or a dict object. The syntax has been designed to give as much flexibility to the user as possible. Thefiltersparameter is typically formed of a singular or repeated units of column reference, comparator string, and value.ComparatorsAvailable comparator strings areFor strings:'IN', 'NOT_IN'For numbers:'>', '>=', '<', '<=', '!=', '=', 'IN', 'NOT_IN'Note thatFor a single column, each of '>'/'>=' or '<'/'<=' can only appear once'='/'!=' can only appear once for each column. Consider using 'IN'/'NOT_IN' for multiple equalities/inequalitiesOnly '>'/'>=' and '<'/'<=' operators can be combined in 'OR' operationsDatetime valuesColumns of type'datetime'have extra flexibilty with regards to values in filters. Values in
a datetime column can of types:datetimeobjects from the pythondatetimemoduletuples of 1-3 integers:(year,),(year, month,),(year, month, day)integer miliseconds since theepoch01/01/1970Tuple syntaxThe below examples are all equivalentfromdatetimeimportdatetime...filters=('Year','>',datetime(2016,1,1))...filters=('Year','>',(2016,1,1))...filters=(table['Year'],'>',(2016,1,1))List of tuples syntaxThe below examples are all equivalentfilters=[('NumberColumn1','<=',10),('NumberColumn1','>=',5)]...filters=[('NumberColumn1','<=',10,'AND','>=',5)]Further examples include filters on multiple columnsfilters=[('NumberColumn1','<=',10),('StringColumn1','IN',['blah','foo'])]Dict syntaxfilters={'NumberColumn1':[('<=',10),('>=',5)],table['StringColumn1']:('IN',['blah','foo'])}AND and ORFilters can be combined via 'OR' or 'AND'. Filters specied via a list of tuples (see above) are combined by 'AND' by default. To use 'OR', the following syntax is accepted...filters=[('NumberColumn1','<=',10,'OR','>=',5)]Note that 'OR' can only be used once per column and cannot be combined with 'AND' on the same column.AggregatesAggregates can be selected for a particular column using theaggregatesparameter. Theaggregatesparameter accepts a tuple/list of tuples/dict of the column-to-aggregrate mapping specifying the aggregate to perform on each column.For example the following are equivalentaggregates=('ColumnName1','sum')...aggregates=(table['ColumnName1'],'sum')...aggregates=[('ColumnName1','sum')]...aggregates={'ColumnName1':'sum'}Aggregate options (case insensitive):Forstringtype columns: 'number', 'distinct', 'min', 'max'Forint,doubleanddatetimetype columns: 'number', 'distinct', 'min', 'max', 'med', 'sum', 'avg', 'med'Note that you cannot use both grouping and aggregate on a column.GroupingsGroupings can be selected for a particular column using thegroupingsparameter. Thegroupingsparameter accepts a tuple/list of tuples/dict of the column-to-aggregrate mapping specifying the grouping to perform on each column.Grouping options (case insensitive):Forint,doubletype columns: 'auto'Fordatetimetype columns: 'year', 'month', 'week', 'day', 'hour', 'minute', 'second'Note that you cannot use both grouping and aggregate on a column.Set chart optionsChart options can be set using thechart_optionsdict parameter. Options that can be set includex_type,y_type,size_type,color_type: set scale of the axis to be eitherlinearorloge.g.{'x_type' : 'linear'}. Note that this cannot be set for an axis representing a 'string' or 'datetime' column. Default islinearfor number columns.type: set chart type to be one ofline,bar,circle,area,autoe.g{'type' : 'circle'}Embedding a visualOnce a Visual object has been created, it can be embedded within a Jupyter notebook with thevisual.embed()method, which returns an IFrame of the embedded representation of the chart oncount.co.Chart sharingA visual can be shared by using thevisual.url()method. This returns a string url of the full visual url oncount.co.Manage your data in CountOverwrite an existing tabletable=count.upload(data=pd,name='MyTableName',overwrite_key='TwPhiNcdxc7')or if the Table object is still in memory,table=table.overwite(data=pd,name='MyTableName')Append to an existing tabletable=count.upload(data=pd,name='MyTableName',append_key='TwPhiNcdxc7')or if the Table object is still in memory,table=table.append(data=pd,name='MyTableName')Note that the new data being appendedmust have a header rowmust have the same number of columns as the original tablemust have the same column types as the original columnColumn typesColumn types of a data file/blob are automatically interpreted on upload tocount.co. Possible column types areint: column of integer valuesdouble: column of floating point valuesdatetime: column of datetime valuesstring: column of wordsShould you wish to force a column to be of a particular type, it is possible to do this by specifying thecolumn_typeslist parameter oncount.uploadortable.overwrite, for example to specify the first 4 column types of a dataset with more than 4 columns:table=count.upload(data=pd,name='MyTableName',column_types=['int','double','double','datetime'])Note thatcolumn_typesparameter cannot be used in conjunction with append methodscolumns that cannot be interpreted as eitherint,double, ordatetimewill be interpreted asstringcolumnsif used in conjunction withcolumn_namesparameter, the length of both lists must be the sameColumn namesDefault column names are taken from the first header of the of the file/data uploaded. Column names can be overridden by specifying thecolumn_nameslist parameter oncount.uploadortable.overwrite, for example to specify the first 4 column names of a dataset with more than 4 columns:table=count.upload(data=pd,name='MyTableName',column_types=['MyColumn1','MyColumn2','MyColumn3','MyColumn4'])Note thatcolumn_namesparameter cannot be used in conjunction with append methodsif used in conjunction withcolumn_namesparameter, the length of both lists must be the sameDelete a tableThis deletes a table oncount.co. As such, any operations on a deleted table will throw error with 404 status codetable.delete()count.delete_table('TwPhiNcdxc7')A Full Example:importpandasaspdfromcount_apiimportCountAPItoken="Use token generated from Count Admin page"count=CountAPI()count.set_api_token(token)#Upload a dataframedf=pd.read_csv('norweiganCarSales.csv')table=count.upload(data=df,name='Car Sales in Norway')#You can view the table and create your own visuals in Count using the table.url() methodurl=table.url()#Preview first 10 lines of tabletable.head()#Get size of tabletable.size()# Create visual of chart of SUM('Quantity') vs 'Year' separated by color for 'Type'# for year between 2007 and end of 2016# with linear scale for y-axis, and line chart typevisual=table.upload_visual(x='Year',y='Quantity',color='Type',aggregates={'Quantity':'sum'},filters=[('Year','>=',(2007,)),('Year','<=',(2016,))]chart_options={'y_type':'linear','chart_type':'line'})# Get visual urlvisual.url()#If using Jupyter notebook, you can also embed a chart viavisual.embed()#Delete table on count.co if no longer neededtable.delete()Technical DocumentationCountAPICountAPI class containing the following methods:set_api_token(api_token)Sets API token obtained fromcount.co.api_token: String API tokenupload(path = None, name = None, data = None, overwrite_key = None)Uploads csv file from path or csv data from str (keyword arg only method).path: String filepath to the .csv or .xls(x). Cannot be used in conjunction withpath.data: String csv data to upload. Cannot be used in conjunction withpath.name: String name of table.overwrite_key: String key of the table for which you would like to replace the data.append_key: String key of the table to which you would like to append data.column_types: List of strings of column types. Acceptable types of column type are 'string', 'int', 'double', and 'datetime'.column_names: List of strings of column names.ifcolumn_names/column_typeshave length greater than the number of columns in the table, the extra enties are ignored.column_names: andcolumn_typesmust have same length if both are set.column_namesandcolumn_typescannot be used in conjuction withappend_keyReturn: Table object.delete_table(table_key):Deletes specified table fromcount.coserver.table_key: String table key.table(table_key):Get a table object from an existing table key.table_key: String table key.Return: Table Object.TableTable class containing the following methods:[index]:Get Column object from column index.index: Integer index of columnReturn: Column Object.[name]:Get Column object from column name. Returns first column found with header matching name.name: String column name.Return: Column Object.append(path = None, data = None):Appends csv file from path or csv data from str (keyword arg only method) to existing table. New table must match column types of existing table.path: String filepath to the .csv or .xls(x). Cannot be used in conjunction withpath.data: String csv data to upload. Cannot be used in conjunction withpath.Return: Self.column(index):Get Column object from column index.index: Integer index of columnReturn: Column Object.column(name):Get Column object from column name. Returns first column found with header matching name.name: String column name.Return: Column Object.columns(name = None):Get list of Column objects with headers matching name parameter. If name is defaulted, returns all columns in table.Return: List of Column Objects.delete():Deletes table fromcount.coserver. Future references to this Table will be undefined.head(rows=10,columns=10):Prints first n rows of tablerows: Integer number of rows requested. Max 100. Default 10.columns: Integer number of columns requested. Max 20. Default 10.tail(rows=10,columns=10):Prints last n rows of tablerows: Integer number of rows requested. Max 100. Default 10.columns: Integer number of columns requested. Max 20. Default 10.overwrite(path = None, name = None, data = None, column_types = None, column_names = None):Uploads csv file from path or csv data from str (keyword arg only method), overwriting existing table. New table must match column types of existing table.path: String filepath to the .csv or .xls(x). Cannot be used in conjunction withpath.data: String csv data to upload. Cannot be used in conjunction withpath.name: String name of table.column_types: List of strings of column types. Acceptable types of column type are 'string', 'int', 'double', and 'datetime'.column_names: List of strings of column names.ifcolumn_names/column_typeshave length greater than the number of columns in the table, the extra enties are ignored.column_names: andcolumn_typesmust have same length if both are set.Return: Self.size():Size of table as a tuple of ints (column_extent, row_extent)Return: Tuple (int, int)upload_visual(x = None, y = None, color = None, size = None, label = None, aggregates = None, filters = None, groupings = None, chart_options = None):Uploads chart visual tocount.co.x: Column object/string column name to be used for x-axisy: Column object/string column name to be used for y-axiscolor: Column object/string column name to be used for color-axissize: Column object/string column name to be used for size-axislabel: Column object/string column name to be used for label-axisaggregates: Tuple/list of tuples/dictionary of aggregates to be applied to columns.filters: Tuple/list of tuples/dictionary of filters to be applied to columns.groupings: Tuple/list of tuples/dictionary of groupings to be applied to columns.chart_options: Dictionary of chart options to be applied. Accepted dict keys:values:type:line,bar,circle,area,autox_type:linear,logy_type:linear,logsize_type:linear,logcolor_type:linear,logReturn: Visual object.url():Get url to table view on count.co.Return: String of URL.VisualVisual class containing the following methods:embed():Returns IFrame to current visual. For use with interactive environments, e.g Jupyter notebooks.ReturnIFrame.download_csv():Download csv of visual oncount.co.Downloads to Downloads folder if path is defaulted.path: str download path.download_preview():Download png of visual oncount.co.Downloads to Downloads folder if path is defaulted.path: str download path.height: int pixels.width: int pixels.preview_url():Returns url to preview view oncount.co.Return: String.set_chart_options(dict: chart_option):Set chart options.chart_options: Dictionary of chart options to be applied. Accepted dict keys:values:type:line,bar,circle,area,autox_type:linear,logy_type:linear,logsize_type:linear,logcolor_type:linear,logReturn: Self.url():Returns url to visual view oncount.co.Return: String.url_embed():Returns url to visual view oncount.cosuitable for embeddingReturn: String.ColumnColumn class containing the following methods:aggregate(aggregate):Add aggregate function to Column object. Note: cannot perform both group_by and aggregate on the same Column object.aggregate: String aggregatestr: ['DISTINCT', 'MIN', 'MAX', 'MED']other: ['DISTINCT', 'MIN', 'MAX', 'MED', 'SUM', 'AVG', 'STD', 'VAR', 'MED']Return: selffilter(comparator, str or int or float or datetime: value):Returns Filter object with specified comparator and valuecomparator: String comparator. Available comparators are:
str: ['IN']
other : ['>', '>=', '<', '<=']value: string/integer/float/datetime value to compare againstReturn: self