Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating the column name for a Panda DataFrame

I'm trying to make nicely formatted tables from pandas. Some of my column names are far too long. The cells for these columns are large cause the whole table to be a mess.

In my example, is it possible to rotate the column names as they are displayed?

data = [{'Way too long of a column to be reasonable':4,'Four?':4},
        {'Way too long of a column to be reasonable':5,'Four?':5}]
pd.DataFrame(data)

I would like to rotate the names of the columns as displayed here.

like image 296
Dan Fiorino Avatar asked Oct 12 '17 17:10

Dan Fiorino


People also ask

How do I rearrange column names in pandas?

Reorder Columns using Pandas . Another way to reorder columns is to use the Pandas . reindex() method. This allows you to pass in the columns= parameter to pass in the order of columns that you want to use.

How do you rotate a column in Python?

Use the T attribute or the transpose() method to swap (= transpose) the rows and columns of pandas. DataFrame . Neither method changes the original object but returns a new object with the rows and columns swapped (= transposed object).

How do you change the position of a column in a DataFrame?

You need to create a new list of your columns in the desired order, then use df = df[cols] to rearrange the columns in this new order.


1 Answers

Something like:

data = [{'Way too long of a column to be reasonable':4,'Four?':4},
        {'Way too long of a column to be reasonable':5,'Four?':5}]
dfoo = pd.DataFrame(data)
dfoo.style.set_table_styles(
    [dict(selector="th",props=[('max-width', '80px')]),
        dict(selector="th.col_heading",
                 props=[("writing-mode", "vertical-rl"), 
                        ('transform', 'rotateZ(-90deg)'),
                        ])]
)

is probably close to what you want:

enter image description here

see result here

like image 118
Bobain Avatar answered Sep 21 '22 15:09

Bobain