简体   繁体   English

Pandas:根据另一列设置数据透视中的单元格样式

[英]Pandas: Style cells in a pivot based on another column

I want to highlight the cells in my pivot based on another column for that cell.我想根据该单元格的另一列突出显示我的数据透视中的单元格。 For eg, I want to highlight the 'Value' based on the 'Color' column.例如,我想根据“颜色”列突出显示“值”。

import pandas as pd

data = { 'Week': [1,2,3,4,5,1,2,3,4,5],
    'Color': ['Green','Red','Green','Yellow','Red','Green','Yellow','Red','Yellow','Red'],
    'Part': ['A','A','A','A','A','B','B','B','B','B'],
    'Value': [10, -20, 20, -20, -10, 10, -5, -8, -9, -10]
    }

df = pd.DataFrame(data)

df_pivot = df.pivot_table(index='Part', columns='Week',values='Value')

Expected output:预期输出:

Unfortunately, I am unable to find relevant examples on my web search to help me out.不幸的是,我无法在我的网络搜索中找到相关示例来帮助我。

Making use of pandas built-in styling functionality:利用熊猫内置的样式功能:

import pandas as pd

# Initialize example dataframe
data = {
    'Week': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
    'Color': ['Green', 'Red', 'Green', 'Yellow', 'Red', 'Green', 'Yellow', 'Red', 'Yellow', 'Red'],
    'Part': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
    'Value': [10, -20, 20, -20, -10, 10, -5, -8, -9, -10]
}
df = pd.DataFrame(data)

# Merge 'Color' and 'Value' columns into one single column
df['Value'] = list(zip(df.Color, df.Value))

# Perform pivot operation
df = df.pivot(index='Part', columns='Week', values='Value')

# Split into two dataframes: a colors dataframe and a numerical values dataframe
color_df = df.applymap(lambda x: x[0])
value_df = df.applymap(lambda x: x[1])

# Transform dataframe with colors into formatting commands
color_df = color_df.applymap(lambda x: f'background-color: {x.lower()}')

# Apply color styling to values dataframe
styled_df = value_df.style.apply(lambda x: color_df, axis=None)
styled_df.to_excel('output.xlsx')

It is simple formula for Seaborn library.这是 Seaborn 库的简单公式。

import matplotlib.pyplot as plt
import seaborn as sns
swarm_plot = sns.heatmap(df_pivot, cmap="YlGnBu", annot=True, cbar=False)
plt.show()

You need to change colors if you want.如果需要,您需要更改颜色。 Please put something for reputation because I am poor :-)请为声誉做点什么,因为我很穷:-)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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