Добавление цвета фона в пандафрейм - PullRequest
1 голос
/ 29 января 2020

У меня есть сводная таблица, созданная с использованием Pandas, которая выглядит следующим образом: enter image description here

Как мне этого добиться?

1 Ответ

1 голос
/ 29 января 2020

Вы можете создать DataFrame стилей с помощью Styler.apply и установить строки по значению индекса с помощью loc:

df = df.reset_index()

def color(x):
    c1 = 'background-color: yellow'
    c2 = 'background-color: orange'
    c3 = 'background-color: green'
    c4 = 'background-color: blue'
    c = '' 
    #compare columns
    mask1 = x['Row Lbl'] == 'cashback'
    mask2 = x['Row Lbl'].isin(['GrandTot', 'with cashbak'])
    both = mask1 | mask2
    #DataFrame with same index and columns names as original filled empty strings
    df1 =  pd.DataFrame(c, index=x.index, columns=x.columns)
    #modify values of df1 column by boolean mask
    df1.loc[~both, 'price'] = c1
    df1.loc[~both, 'GrandTot'] = c2
    df1.loc[mask1, :] = c3
    df1.loc[mask2, :] = c4
    return df1

df.style.apply(color, axis=None).to_excel('styled.xlsx', engine='openpyxl', index=False)
...