python - Pretty Printing a pandas dataframe - Stack Overflow

Ask questions Research chat →

https://stackoverflow.com/questions/18528533/pretty-printing-a-pandas-dataframe · scraped

python

Attachments

Scraped Content

— 159 words · 2026-02-14 03:19:02 UTC ·

Excerpt

Maybe you're looking for something like this: def tableize(df): if not isinstance(df, pd.DataFrame): return df_columns = df.columns.tolist() max_len_in_lst = lambda lst: len(sorted(lst, reverse=True, key=len)[0]) align_center = lambda st, sz: "{0}{1}{0}".format(" "*(1+(sz-len(st))//2), st)[:sz] if len(st) < sz else st align_right = lambda st, sz: "{0}{1} ".format(" "*(sz-len(st)-1), st) if len(st) < sz else st max_col_len = max_len_in_lst(df_columns) max_val_len_for_col = dict([(col, max_len_in_lst(df.iloc[:,idx].astype('str'))) for idx, col in enumerate(df_columns)]) col_sizes = dict([(col, 2 + max(max_val_len_for_col.get(col, 0), max_col_len)) for col in df_columns]) build_hline = lambda row: '+'.join(['-' * col_sizes[col] for col in row]).join(['+', '+']) build_data = lambda row, align: "|".join([align(str(val), col_sizes[df_columns[idx]]) for idx, val in enumerate(row)]).join(['|', '|']) hline = build_hline(df_columns) out =
Maybe you're looking for something like this: def tableize(df): if not isinstance(df, pd.DataFrame): return df_columns = df.columns.tolist() max_len_in_lst = lambda lst: len(sorted(lst, reverse=True, key=len)[0]) align_center = lambda st, sz: "{0}{1}{0}".format(" "*(1+(sz-len(st))//2), st)[:sz] if len(st) < sz else st align_right = lambda st, sz: "{0}{1} ".format(" "*(sz-len(st)-1), st) if len(st) < sz else st max_col_len = max_len_in_lst(df_columns) max_val_len_for_col = dict([(col, max_len_in_lst(df.iloc[:,idx].astype('str'))) for idx, col in enumerate(df_columns)]) col_sizes = dict([(col, 2 + max(max_val_len_for_col.get(col, 0), max_col_len)) for col in df_columns]) build_hline = lambda row: '+'.join(['-' * col_sizes[col] for col in row]).join(['+', '+']) build_data = lambda row, align: "|".join([align(str(val), col_sizes[df_columns[idx]]) for idx, val in enumerate(row)]).join(['|', '|']) hline = build_hline(df_columns) out = [hline, build_data(df_columns, align_center), hline] for _, row in df.iterrows(): out.append(build_data(row.tolist(), align_right)) out.append(hline) return "\n".join(out) df = pd.DataFrame([[1, 2, 3], [11111, 22, 333]], columns=['a', 'b', 'c']) print tableize(df) Output: +-------+----+-----+ | a | b | c | +-------+----+-----+ | 1 | 2 | 3 | | 11111 | 22 | 333 | +-------+----+-----+

Visibility

Visible to everyone

Reading Status

Related Bookmarks

My Note


Saved!

Annotations

Export as Markdown
+ Annotate selection

Add Annotation