Column name designation in Python Pandas DataFrame or Jupyter Notebooks

I have long headers for some of my columns in my data frame, and I would like them to wrap text. I know that this functionality is built into pandas, just like me:

pd.DataFrame(np.random.randn(2, 10), 
    columns=['Very Long Column Title ' + str(i) for i in range(10)])

DataFrame with wrapped column names

But if I have fewer columns, the headers will not wrap:

pd.DataFrame(np.random.randn(10, 2), 
    columns=['Very Long Column Title ' + str(i) for i in range(2)])

DataFrame does not include column names

I also tried manually inserting a new line:

import pandas as pd    
pd.DataFrame(np.random.randn(10, 2), 
    columns=['Very Long \n Column Title ' + str(i) for i in range(2)])

But this gives the same result as above.

I found similar answers on this topic:

Jupyter, , , pandas.

+8
4

, IPython:

df = pd.DataFrame(np.random.randn(10, 2), 
    columns=['Very Long Column Title ' + str(i) for i in range(2)])
df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])])
+5

Jupyter . pandas , , pandas , , HTML.

Jupyter Notebook , , :

from IPython.core.display import HTML
HTML("<style>.rendered_html th {max-width: 120px;}</style>")

, html 120 .

+6

"" , :

def colfix(df, L=5): return df.rename(columns=lambda x: ' '.join(x.replace('_', ' ')[i:i+L] for i in range(0,len(x),L)) if df[x].dtype in ['float64','int64'] else x )

colfix(your_df)

. fooobar.com/questions/793580/...

0

textwrap:

import textwrap

cols = ['Very Long Column Title ' + str(i) for i in range(2)]

# Split wide columns, you can then join these with any delimiter you'd like
cols = [textwrap.wrap(x, width=20) for x in cols]

# print(cols)
# [['Very Long Column', 'Title 0'], ['Very Long Column', 'Title 1']]

0

Source: https://habr.com/ru/post/1016134/


All Articles