python - 熊猫:基于另一列的枢轴中的样式单元格
问题描述
我想基于该单元格的另一列突出显示我的数据透视中的单元格。例如,我想根据“颜色”列突出显示“值”。
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
# 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')
推荐阅读
- c# - 当我添加分数时, scoreText 只是快速显示添加到自身的分数
- javascript - 当我单击导航栏上的锚点时,它会将我带到那里,但部分内容被导航栏本身隐藏
- c# - 我的链表 DeleteAt 函数有什么问题?
- flutter - 我在运行我的颤振应用程序时遇到错误
- html - 当元标记告诉更多关于文件的信息时,为什么我们使用 lang 属性作为 html 属性?
- java - android java sqlite中的空指针异常
- java - android中glide的缓存时间段
- javascript - FormData 到对象的格式与节点 bodyparser 相同
- wordpress - 无法在 Elementor 中创建标题
- sql - Oracle SQL query to pivot like excel