Pandas:在基于另一列的数据透视图中设置单元格的样式

时间:2019-02-11 20:15:55

标签: python 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_pivot = df.pivot_table(index='Part', columns='Week',values='Value')

预期输出:

很遗憾,我无法在网络搜索中找到相关示例来帮助我。

2 个答案:

答案 0 :(得分:1)

使用熊猫内置的styling功能:

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')

答案 1 :(得分:0)

这是Seaborn库的简单公式。

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

如果需要,您需要更改颜色。 因为我很贫穷,所以请放点名声:-)

enter image description here