Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display column name different from dictionary key name in Pandas?

Tags:

pandas

I am new to Pandas and see that there are numerous ways to change column headers. For example, the set_axis command works like this :

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.arange(3),columns=['a'])
>>> df
   a
0  0
1  1
2  2
>>> df["a"][0]
0
>>> df.set_axis(['A'],axis=1,inplace=True)
>>> df
   A
0  0
1  1
2  2
>>> df["A"][0]  
0

EDIT : Alternatively, one can use

df.columns = ['A']

to change the column name.

But now, it seems that if I want to change the column header for display purposes only (because the header label is inconvenient to use as a dictionary key), I have to create an entirely new data frame :

>>> df_pretty = df.set_axis(['Long label (%)'],axis=1,inplace=False)
df_pretty
   Long label (%)
0               0  
1               1
2               2

Is this right? Or am I missing something? It seems a waste of memory to have to recreate a new data frame just for printing. I would have thought that Pandas would have a way to store an internal "key" and a separate column label, used only for display purposes.

like image 357
Donna Avatar asked Sep 20 '25 08:09

Donna


1 Answers

The solution posted by @JohnE looks like the best way to go.

I also would like to use a format string, and so add a few more details here :

import pandas
df = pandas.DataFrame({'a' : [1,2,3],'b' : [4,5,6]})
di = {'a' : 'A (J/K*kg)', 'b' : 'B (N/m^2)'}
fstr = {di["a"] : '{:6.2f}', di["b"]:'{:5.2e}'}
df.rename(columns=di).style.format(fstr) 

This, rendered in a Juptyer notebook, looks perfect, and does exactly what I would want.

enter image description here

When I tried the same code at the Python prompt, though, the styler doesn't render.

>>> import pandas
>>> df = pandas.DataFrame({'a' : [1,2,3],'b' : [4,5,6]})
>>> di = {'a' : 'A (J/K*kg)', 'b' : 'B (N/m^2)'}
>>> fstr = {di["a"] : '{:6.2f}', di["b"]:'{:5.2e}'}
>>> df.rename(columns=di).style.format(fstr)
<pandas.io.formats.style.Styler object at 0x105812eb8>

EDIT : In interactive mode, (not in a Jupyter notebook), HTML formatting doesn't display, and it seems that Pandas does not have a basic ascii output style for tables.

like image 119
Donna Avatar answered Sep 23 '25 13:09

Donna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!