Pandas DataFrame styler - How to style pandas dataframe as excel table?

2024/9/27 23:33:22

enter image description here

How to style the pandas dataframe as an excel table (alternate row colour)?

Sample style:

enter image description here

Sample data:

import pandas as pd
import seaborn as snsdf = sns.load_dataset("tips")
Answer

If your final goal is to save to_excel, the only way to retain the styling after export is using the apply-based methods:

  • df.style.apply / df.style.applymap are the styling counterparts to df.apply / df.applymap and work analogously
  • df.style.apply_index / df.style.applymap_index are the index styling counterparts (requires pandas 1.4.0+)

For the given sample, use df.style.apply to style each column with alternating row colors and df.style.applymap_index to style all row/col indexes:

css_alt_rows = 'background-color: powderblue; color: black;'
css_indexes = 'background-color: steelblue; color: white;'(df.style.apply(lambda col: np.where(col.index % 2, css_alt_rows, None)) # alternating rows.applymap_index(lambda _: css_indexes, axis=0) # row indexes (pandas 1.4.0+).applymap_index(lambda _: css_indexes, axis=1) # col indexes (pandas 1.4.0+)
).to_excel('styled.xlsx', engine='openpyxl')


If you only care about the appearance in Jupyter, another option is to set properties for targeted selectors using df.style.set_table_styles (requires pandas 1.2.0+):

# pandas 1.2.0+
df.style.set_table_styles([{'selector': 'tr:nth-child(even)', 'props': css_alt_rows},{'selector': 'th', 'props': css_indexes},
])
https://en.xdnf.cn/q/71406.html

Related Q&A

Remove namespace with xmltodict in Python

xmltodict converts XML to a Python dictionary. It supports namespaces. I can follow the example on the homepage and successfully remove a namespace. However, I cannot remove the namespace from my XM…

Groupby count only when a certain value is present in one of the column in pandas

I have a dataframe similar to the below mentioned database:+------------+-----+--------+| time | id | status |+------------+-----+--------+| 1451606400 | id1 | Yes || 1451606400 | id1 | Yes …

how to save tensorflow model to pickle file

I want to save a Tensorflow model and then later use it for deployment purposes. I dont want to use model.save() to save it because my purpose is to somehow pickle it and use it in a different system w…

PySide2 Qt3D mesh does not show up

Im diving into Qt3D framework and have decided to replicate a simplified version of this c++ exampleUnfortunately, I dont see a torus mesh on application start. Ive created all required entities and e…

Unable to import module lambda_function: No module named psycopg2._psycopg aws lambda function

I have installed the psycopg2 with this command in my package folder : pip install --target ./package psycopg2 # Or pip install -t ./package psycopg2now psycopg2 module is in my package and I have crea…

RestrictedPython: Call other functions within user-specified code?

Using Yuri Nudelmans code with the custom _import definition to specify modules to restrict serves as a good base but when calling functions within said user_code naturally due to having to whitelist e…

TypeError: object of type numpy.int64 has no len()

I am making a DataLoader from DataSet in PyTorch. Start from loading the DataFrame with all dtype as an np.float64result = pd.read_csv(dummy.csv, header=0, dtype=DTYPE_CLEANED_DF)Here is my dataset cla…

VS Code Pylance not highlighting variables and modules

Im using VS Code with the Python and Pylance extensions. Im having a problem with the Pylance extension not doing syntax highlight for things like modules and my dataframe. I would expect the modules…

How to compute Spearman correlation in Tensorflow

ProblemI need to compute the Pearson and Spearman correlations, and use it as metrics in tensorflow.For Pearson, its trivial :tf.contrib.metrics.streaming_pearson_correlation(y_pred, y_true)But for Spe…

Pytorch loss is nan

Im trying to write my first neural network with pytorch. Unfortunately, I encounter a problem when I want to get the loss. The following error message: RuntimeError: Function LogSoftmaxBackward0 return…