3

I would like to wrap the column names of a data frame to some specific width. For instance, transform

   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
0                       -1.526078                        0.258110
1                        0.263490                       -0.268635
2                       -1.264121                       -1.257454

to something like

   aaaaaaaaaaaaaaaaa  aaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaa      aaaaaaaaaaaaa
0      -1.526078         0.258110
1       0.263490        -0.268635
2      -1.264121        -1.257454

There is a solution to this problem in this stackoverflow post, but it only works in jupyter notebooks, not in regular python.

Code to reproduce the dataframe:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 2), columns=['a' * 30] * 2)
print(df)
BiBi
  • 7,418
  • 5
  • 43
  • 69
  • did you check this: https://stackoverflow.com/questions/43092345/wrapping-column-names-in-python-pandas-dataframe-or-jupyter-notebooks – YOLO Dec 01 '18 at 18:53
  • 1
    This is the question I mentioned in my post. The answers provided in this thread work only for jupyter notebooks. – BiBi Dec 01 '18 at 19:13

1 Answers1

-1

You could wrap the DataFrame in your own class which would override the __str__ and/or __repr__ methods to achieve this.

sophros
  • 14,672
  • 11
  • 46
  • 75