Python 有没有办法对熊猫中的数据帧进行颜色编码?如果一列上的条件匹配,则对另一列进行颜色编码
我有一个熊猫数据框,里面有多列。我有一项任务,如果条件与C列中的条件相匹配,则对a列中的特定单元格进行颜色编码。 我附上了一个例子。 我想对C列应用三个不同的条件Python 有没有办法对熊猫中的数据帧进行颜色编码?如果一列上的条件匹配,则对另一列进行颜色编码,python,pandas,dataframe,styles,Python,Pandas,Dataframe,Styles,我有一个熊猫数据框,里面有多列。我有一项任务,如果条件与C列中的条件相匹配,则对a列中的特定单元格进行颜色编码。 我附上了一个例子。 我想对C列应用三个不同的条件 1. If Column C = poor than Column A = red color 2. If Column C = good then Column A = Orange color 3. If Column C = very good then Column A = Green color 提前谢谢 与自定
1. If Column C = poor than Column A = red color
2. If Column C = good then Column A = Orange color
3. If Column C = very good then Column A = Green color
提前谢谢 与自定义功能一起使用,用于根据条件选择颜色:
df = pd.DataFrame({
'A':[1,3,5,7],
'B':list('abcd'),
'C':['poor','good','very good','unknown'],
})
print (df)
A B C
0 1 a poor
1 3 b good
2 5 c very good
3 7 d unknown
到目前为止你试过什么?请看一看你应该如何提问。
def color(x):
c1 = 'background-color: red'
c2 = 'background-color: orange'
c3 = 'background-color: green'
c = 'background-color: '
m1 = x['C'] == 'poor'
m2 = x['C'] == 'good'
m3 = x['C'] == 'very good'
df = pd.DataFrame(c, index=x.index, columns=x.columns)
df['A'] = np.select([m1, m2, m3], [c1, c2, c3], default=c)
return df
df.style.apply(color,axis=None)
#if want output in excel file
#df.style.apply(color,axis=None).to_excel('styled.xlsx', engine='openpyxl', index=False)