简体   繁体   中英

How do I style only the last row of a pandas dataframe?

I can style a pandas dataframe:

import pandas as pd
import numpy as np
import seaborn as sns
cm = sns.diverging_palette(-5, 5, as_cmap=True)

df = pd.DataFrame(np.random.randn(3, 4))
df.style.background_gradient(cmap=cm)

将样式应用于所有行的数据框

but I can't figure out how to only apply a style to the last row. There is a subset option in the background_gradient call, and it suggests that I use an index slice but I cannot figure out how to make just the last row have any kind of styling.

Here is my closest to success:

df.style.background_gradient(cmap=cm, subset=[2], axis='index')

第三列,不是最后一行样式

Use the last element of your index as your subset.

df.style.background_gradient(cmap=cm, axis=1, subset=df.index[-1])

在此处输入图片说明

You could also use pd.IndexSlice which is useful if you want to apply the style to multiple rows, including the last:

import pandas as pd
import numpy as np
import seaborn as sns


cm = sns.diverging_palette(-5, 5, as_cmap=True)
df = pd.DataFrame(np.random.randn(3, 4))

indices = pd.IndexSlice[[0, df.last_valid_index()], :]
df.style.background_gradient(cmap=cm, axis=1, subset=indices)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM