Render a DataFrame to a LaTeX tabular/longtable environment output.
160361
def write_result(self, buf):
        

        # string representation of the columns
        if len(self.frame.columns) == 0 or len(self.frame.index) == 0:
            info_line = ('Empty {name}\nColumns: {col}\nIndex: {idx}'
                         .format(name=type(self.frame).__name__,
                                 col=self.frame.columns,
                                 idx=self.frame.index))
            strcols = [[info_line]]
        else:
            strcols = self.fmt._to_str_columns()

        def get_col_type(dtype):
            if issubclass(dtype.type, np.number):
                return 'r'
            else:
                return 'l'

        # reestablish the MultiIndex that has been joined by _to_str_column
        if self.fmt.index and isinstance(self.frame.index, ABCMultiIndex):
            out = self.frame.index.format(
                adjoin=False, sparsify=self.fmt.sparsify,
                names=self.fmt.has_index_names, na_rep=self.fmt.na_rep
            )

            # index.format will sparsify repeated entries with empty strings
            # so pad these with some empty space
            def pad_empties(x):
                for pad in reversed(x):
                    if pad:
                        break
                return [x[0]] + [i if i else ' ' * len(pad) for i in x[1:]]
            out = (pad_empties(i) for i in out)

            # Add empty spaces for each column level
            clevels = self.frame.columns.nlevels
            out = [[' ' * len(i[-1])] * clevels + i for i in out]

            # Add the column names to the last index column
            cnames = self.frame.columns.names
            if any(cnames):
                new_names = [i if i else '{}' for i in cnames]
                out[self.frame.index.nlevels - 1][:clevels] = new_names

            # Get rid of old multiindex column and add new ones
            strcols = out + strcols[1:]

        column_format = self.column_format
        if column_format is None:
            dtypes = self.frame.dtypes._values
            column_format = ''.join(map(get_col_type, dtypes))
            if self.fmt.index:
                index_format = 'l' * self.frame.index.nlevels
                column_format = index_format + column_format
        elif not isinstance(column_format, str):  # pragma: no cover
            raise AssertionError('column_format must be str or unicode, '
                                 'not {typ}'.format(typ=type(column_format)))

        if not self.longtable:
            buf.write('\\begin{{tabular}}{{{fmt}}}\n'
                      .format(fmt=column_format))
            buf.write('\\toprule\n')
        else:
            buf.write('\\begin{{longtable}}{{{fmt}}}\n'
                      .format(fmt=column_format))
            buf.write('\\toprule\n')

        ilevels = self.frame.index.nlevels
        clevels = self.frame.columns.nlevels
        nlevels = clevels
        if self.fmt.has_index_names and self.fmt.show_index_names:
            nlevels += 1
        strrows = list(zip(*strcols))
        self.clinebuf = []

        for i, row in enumerate(strrows):
            if i == nlevels and self.fmt.header:
                buf.write('\\midrule\n')  # End of header
                if self.longtable:
                    buf.write('\\endhead\n')
                    buf.write('\\midrule\n')
                    buf.write('\\multicolumn{{{n}}}{{r}}{{{{Continued on next '
                              'page}}}} \\\\\n'.format(n=len(row)))
                    buf.write('\\midrule\n')
                    buf.write('\\endfoot\n\n')
                    buf.write('\\bottomrule\n')
                    buf.write('\\endlastfoot\n')
            if self.fmt.kwds.get('escape', True):
                # escape backslashes first
                crow = [(x.replace('\\', '\\textbackslash ')
                         .replace('_', '\\_')
                         .replace('%', '\\%').replace('$', '\\$')
                         .replace('#', '\\#').replace('{', '\\{')
                         .replace('}', '\\}').replace('~', '\\textasciitilde ')
                         .replace('^', '\\textasciicircum ')
                         .replace('&', '\\&')
                         if (x and x != '{}') else '{}') for x in row]
            else:
                crow = [x if x else '{}' for x in row]
            if self.bold_rows and self.fmt.index:
                # bold row labels
                crow = ['\\textbf{{{x}}}'.format(x=x)
                        if j < ilevels and x.strip() not in ['', '{}'] else x
                        for j, x in enumerate(crow)]
            if i < clevels and self.fmt.header and self.multicolumn:
                # sum up columns to multicolumns
                crow = self._format_multicolumn(crow, ilevels)
            if (i >= nlevels and self.fmt.index and self.multirow and
                    ilevels > 1):
                # sum up rows to multirows
                crow = self._format_multirow(crow, ilevels, i, strrows)
            buf.write(' & '.join(crow))
            buf.write(' \\\\\n')
            if self.multirow and i < len(strrows) - 1:
                self._print_cline(buf, i, len(strcols))

        if not self.longtable:
            buf.write('\\bottomrule\n')
            buf.write('\\end{tabular}\n')
        else:
            buf.write('\\end{longtable}\n')
1302775
def output(data, **kwargs):
    '''
    
    '''

    rows = _find_durations(data)

    kwargs['opts'] = __opts__
    kwargs['rows_key'] = 'rows'
    kwargs['labels_key'] = 'labels'

    to_show = {'labels': ['name', 'mod.fun', 'duration (ms)'],
               'rows':   rows}

    return table_out.output(to_show, **kwargs)
82195
def iter_to_table(value):
    """"""
    if isinstance(value, list):
        return _format_list(value)
    if isinstance(value, dict):
        return _format_dict(value)
    return value
907618
def to_html(self, show_mean=None, sortable=None, colorize=True, *args,
                **kwargs):
        """"""
        if show_mean is None:
            show_mean = self.show_mean
        if sortable is None:
            sortable = self.sortable
        df = self.copy()
        if show_mean:
            df.insert(0, 'Mean', None)
            df.loc[:, 'Mean'] = ['%.3f' % self[m].mean() for m in self.models]
        html = df.to_html(*args, **kwargs)  # Pandas method
        html, table_id = self.annotate(df, html, show_mean, colorize)
        if sortable:
            self.dynamify(table_id)
        return html
148674
def _display_runner(rows,
                    labels,
                    title,
                    display=_DEFAULT_DISPLAY,
                    outputter=_DEFAULT_OUTPUTTER):
    '''
    
    '''
    if display:
        if outputter == 'table':
            ret = salt.output.out_format({'rows': rows, 'labels': labels},
                                         'table',
                                         __opts__,
                                         title=title,
                                         rows_key='rows',
                                         labels_key='labels')
        else:
            ret = salt.output.out_format(rows,
                                         outputter,
                                         __opts__)
        print(ret)
    else:
        return rows
622606
function render() {return df_cc_n(df_map_k($this->_blocks, function($selector, array $rules) {
		/** @var string $selector */ /** @var string[] $rules */
		$rulesS = df_tab_multiline(df_cc_n($rules)); /** @var string $rulesS */
		return "{$selector} {\n{$rulesS}\n}";
	}));}
677041
def print_format_output(dataframe):
    
    print_df = pd.DataFrame()
    dropped_cols = []
    empty_cols = []
    # column display priority is based on the info_keys passed in
    for i, col in enumerate(dataframe):
        if dataframe[col].isnull().all():
            # Don't add col to print_df if is fully empty
            empty_cols += [col]
            continue

        print_df[col] = dataframe[col]
        test_table = tabulate(print_df, headers="keys", tablefmt="psql")
        if str(test_table).index("\n") > TERM_WIDTH:
            # Drop all columns beyond terminal width
            print_df.drop(col, axis=1, inplace=True)
            dropped_cols += list(dataframe.columns)[i:]
            break

    table = tabulate(
        print_df, headers="keys", tablefmt="psql", showindex="never")

    print(table)
    if dropped_cols:
        print("Dropped columns:", dropped_cols)
        print("Please increase your terminal size to view remaining columns.")
    if empty_cols:
        print("Empty columns:", empty_cols)

    return table, dropped_cols, empty_cols
197580
def from_dataframe(dataframe, table_name=""):
        

        return TableData(table_name, list(dataframe.columns.values), dataframe.values.tolist())
66349
def to_json(df, columns, confidence={}):
        """"""
        records = []

        display_cols = list(columns.keys())
        if not display_cols:
            display_cols = list(df.columns)

        bounds = {}
        for c in confidence:
            bounds[c] = {
                "min": df[confidence[c]["lower"]].min(),
                "max": df[confidence[c]["upper"]].max(),
                "lower": confidence[c]["lower"],
                "upper": confidence[c]["upper"]
            }

        labels = {}
        for c in display_cols:
            if "label" in columns[c]:
                labels[c] = columns[c]["label"]
            else:
                labels[c] = c

        for i, row in df.iterrows():
            row_ = DataTable.format_row(row, bounds, columns)
            records.append({labels[c]: row_[c] for c in display_cols})

        return {
            "data": records,
            "columns": [{"data": labels[c]} for c in display_cols]
        }
6745
def normalize(df):
    """"""
    # in ipython notebook, explore and describe the DataFrame columns
    print('Of the {} columns, {} are actually DataFrames'.format(len(df.columns), sum([not isinstance(df[col], pd.Series) for col in df.columns])))
    # remove dataframes with only 2 columns and one is the _str of the other:
    for col in df.columns:
        if isinstance(df[col], pd.DataFrame):
            print('Column {} is a {}-wide DataFrame'.format(col, len(df[col].columns)))
            if df[col].columns[1] == df[col].columns[0] + '_str':
                print('Column {} looks easy because it has sub-columns {}'.format(col, df[col].columns))
                df[col] = df[col][df[col].columns[1]]
            else:
                try:
                    assert(float(df[col].iloc[:, 0].max()) == float(df[col].iloc[:, 1].max()))
                    df[col] = df[col].fillna(-1, inplace=False)
                    series = pd.Series([int(Decimal(x)) for x in df[col].iloc[:, 1].values]).astype('int64').copy()
                    del df[col]
                    df[col] = series
                    print('Finished converting column {} to type {}({})'.format(col, type(df[col]), df[col].dtype))
                except:
                    print_exc()

    print('Of the {} columns, {} are still DataFrames after trying to convert both columns to long integers'.format(
        len(df.columns), sum([not isinstance(df[col], pd.Series) for col in df.columns])))
    return df
526586
def pretty_print_table_instance(table):
    """"""
    assert isinstance(table, Table)

    def pretty_print_row(styled, plain):
        """Pretty print a row."""
        click.secho(
            " | ".join(
                v + " " * (table.column_widths[k] - len(plain[k]))
                for k, v in enumerate(styled)
            )
        )

    pretty_print_row(table.headers, table.plain_headers)
    for k, row in enumerate(table.rows):
        pretty_print_row(row, table.plain_rows[k])
426787
def dataframe(df, **kwargs):
    
    table(df.values, list(df.columns), **kwargs)
428546
def to_string(self, verbose=0):
        """"""
        rows = [[it + 1] + list(map(str, (self[k][it] for k in self.keys())))
                for it in range(self.num_iterations)]

        return tabulate(rows, headers=["Iter"] + list(self.keys()))
777635
def render_dictionary(data, headers=None):
  
  return IPython.core.display.HTML(_html.HtmlBuilder.render_table(data, headers))
137796
def _render_corpus_row(self, label, ngrams):
        """"""
        row = ('<tr>\n<td>{label}</td>\n<td>{first}</td>\n<td>{only}</td>\n'
               '<td>{last}</td>\n</tr>')
        cell_data = {'label': label}
        for period in ('first', 'only', 'last'):
            cell_data[period] = ', '.join(ngrams[label][period])
        return row.format(**cell_data)
343287
def render_table(data, headers=None):
    
    builder = HtmlBuilder()
    builder._render_objects(data, headers, datatype='dict')
    return builder._to_html()
230763
def display_charts(df, chart_type="default", render_to=None, **kwargs):
    
    if chart_type not in ("default", "stock"):
        raise ValueError("Wrong chart_type: accept 'default' or 'stock'.")
    chart_id = render_to if render_to is not None else _generate_div_id_chart()
    json_data = serialize(df, render_to=chart_id, chart_type=chart_type,
                          **kwargs)
    content = """<div id="{chart_id}"</div>
    <script type="text/javascript">{data}</script>"""
    return display(HTML(content.format(chart_id=chart_id,
                                       data=json_data)))