Ad
Export Styled Pandas Data Frame To Excel
I'm trying to export a stylish data frame to an exel file using the scrpit bellow
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4),
columns=list('BCDE'))],axis=1)
df.iloc[0, 2] = np.nan
def highlight_greater(x):
r = 'red'
g = 'gray'
m1 = x['B'] > x['C']
m2 = x['D'] > x['E']
df1 = pd.DataFrame('background-color: ', index=x.index, columns=x.columns)
#rewrite values by boolean masks
df1['B'] = np.where(m1, 'background-color: {}'.format(r), df1['B'])
df1['D'] = np.where(m2, 'background-color: {}'.format(g), df1['D'])
return df1
df.style.apply(highlight_greater, axis=None).to_excel('df.xlsx', engine='openpyxl')
It works well, but when I open the file the background is black when the condition does not match, an idea to solve this problem ?
Ad
Answer
You can create DataFrame
filled by empty values in function:
def highlight_greater(x):
r = 'red'
g = 'gray'
m1 = x['B'] > x['C']
m2 = x['D'] > x['E']
#if not match return empty string
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
#rewrite values by boolean masks
df1['B'] = np.where(m1, 'background-color: {}'.format(r), df1['B'])
df1['D'] = np.where(m2, 'background-color: {}'.format(g), df1['D'])
return df1
df.style.apply(highlight_greater, axis=None).to_excel('df.xlsx', engine='openpyxl')
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad