我想基于该单元格的另一列突出显示我的数据库中的单元格。例如,我想基于“颜色”列突出显示“值”。
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')
预期产量:

解决办法:
利用pandas内置样式功能:
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['Value'] = list(zip(df.Color, df.Value))
df = df.pivot(index='Part', columns='Week', values='Value')
color_df = df.applymap(lambda x: x[0])
value_df = df.applymap(lambda x: x[1])
color_df = color_df.applymap(lambda x: f'background-color: {x.lower()}')
styled_df = value_df.style.apply(lambda x: color_df, axis=None)
styled_df.to_excel('output.xlsx')








暂无数据