Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the font-size of text in dataframe using pandas

I have studied the styling documentation of pandas but not able to exactly get a particular and precise answer of my question. I am reading an excel file using dataframe and processing that dataframe in my program. At last I am writing processed dataframe in another existing excel file using xlwings library.

I am using-

import pandas as pd
import xlwings as xw
df = pd.read_excel("file.xlsx")

.
.  #Code for processing dataframe and writing dataframe in another excel file
.

Before writing this dataframe in another existing excel I want to change the font-size of whole text inside my final dataframe. I am not able to get the way to do it.

I have found following code in pandas styling document to achieve it-

def magnify():
    return [dict(selector="th",
                 props=[("font-size", "4pt")]),
            dict(selector="td",
                 props=[('padding', "0em 0em")]),
            dict(selector="th:hover",
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
]

I have used above code in my program but font-size of my dataframe remains same.It creates no effect to font-size. I have tried some other methods using styling also but font-size remains same.

Can anyone please tell me in very simple manner how to only change the font-size of my final dataframe using pandas or any other library. Because I have tried many ways but none of ways works for me.I only want to change the font-size and not want to do more styling with my font.

like image 244
Vishav Gupta Avatar asked Dec 11 '19 10:12

Vishav Gupta


1 Answers

You can set one or more properties for each cell using set_properties().

df = pd.DataFrame({
    'date': ('2019-11-29', '2016-11-28'),
    'price': (0, 1),
})

df = df.style.set_properties(**{
    'background-color': 'grey',
    'font-size': '20pt',
})
df.to_excel('test.xlsx', engine='openpyxl')

Also you can use apply() method to customize specific cells:

def custom_styles(val):
    # price column styles
    if val.name == 'price':
        styles = []
        # red prices with 0
        for i in val:
            styles.append('color: %s' % ('red' if i == 0 else 'black'))
        return styles
    # other columns will be yellow
    return ['background-color: yellow'] * len(val)


df = pd.DataFrame(...)
df = df.style.apply(custom_styles)
df.to_excel('test.xlsx', engine='openpyxl')

Also you can use applymap method which works elementwise. You can find more examples in docs.

Hope this helps.

like image 93
Danila Ganchar Avatar answered Nov 07 '22 11:11

Danila Ganchar