首页 > 解决方案 > 突出显示前 10 名,按数据框中的顺序记录

问题描述

需要帮助突出显示数量最多的前 10 家商店。销售额

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt
% matplotlib inline 
import seaborn as sns 

store = pd.read_csv("https://github.com/Kevin-ck1/Intro-To-Data-Science/blob/master/Clothing.csv")

store.head()

数据集的变量名如下图

tsale   sales   margin  nown    nfull   npart   naux    hoursw  hourspw     inv1    inv2    ssize   start

标签: pythonpandasdata-visualization

解决方案


当然!我们可以通过首先找到前 10 家商店的索引来做到这一点。一旦我们这样做了,我们对每一行应用一个样式函数并检查当前行索引(这里存储在 中row.name)是否在前 10 个商店的先前标识的索引中。如果是:我们返回一个突出显示该行的列表,如果不是:我们根本不设置该行的样式。

def highlight_top(df, n=1):
    def _highlight_top(row, index):
        if row.name in index:
            return ["background-color: yellow" for _ in row]
        return ["" for _ in row]
    
    top_stores = df.nlargest(n, "sales")
    top_idx = top_stores.index.values
    return df.style.apply(_highlight_top, index=top_idx, axis=1)
    
# subset our data for testing purposes by only taking the first 10 rows
test_data = store.head(10)

# highlight the top 5 stores in terms of sales
highlight_top(test_data, n=5)

在此处输入图像描述


推荐阅读